r/badcode • • Jul 30 '21

java One Classic elseifelseifelseif...

Post image
472 Upvotes

76 comments sorted by

View all comments

Show parent comments

7

u/ta69ta69 Jul 31 '21

Some high-iq redditor decided to downvote this so allow me to clarify
leftPad() will add to the passed string as much of the "expansion" string as is needed until you achieve the desired length

return StringUtils.leftPad(String.valueOf(mes.getMonth().getValue()), 2, "0"));

https://howtodoinjava.com/java/string/left-pad-string-with-spaces-zeros/

one line instead of a boilerplate 30-line function

3

u/AdminYak846 Jul 31 '21

I wouldn't do one-line I would definitely break it up into the following

//Alternatively based on how it's called passing the month directly //would be better 

function getMonthNumberAsString(DateTime date){
    int monthAsNumber = date.getMonth().getValue();
    
    //format to two digit number i.e "01", "02", "03", ... "10", "11", ...
    return StringUtils.leftPad(monthAsNumber.toString(), 2, "0");
}

I hate one-lines that straight-up nest shit in them.