Below I have methods to return month name. In first one implementation I use switch/case, this method is longer and validation is in the last line. On second one I make validation in first line and instead of switch/case I declared table with months name.
Which one is better when I think about KISS and DRY principles?
public String getMonthName(int month) {
switch (month) {
case 1:
return "January";
case 2:
return "February";
case 3:
return "March";
case 4:
return "April";
case 5:
return "May";
case 6:
return "June";
case 7:
return "July";
case 8:
return "August";
case 9:
return "September";
case 10:
return "October";
case 11:
return "November";
case 12:
return "December";
default:
throw new IllegalArgumentException("month must be in range 1 to 12");
}
}
Or maybe this one?
public String getMonthNameNew(int month) {
if ((month < 1) || (month > 12)) throw new IllegalArgumentException("month must be in range 1 to 12");
String[] months = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
return months[month - 1];
}
I find the second one easier to read. It's shorter and with a precondition check which immediately tells you what values are allowed. In the first example you have to go through the entire method body to understand that.
Saying all the above the method should be written using java.time.Month
as:
public String getMonthNameNew(int month) {
return Month.of(month).getDisplayName(TextStyle.FULL, Locale.ENGLISH);
}