下面我有返回月份名称的方法。在第一个实现中,我使用 switch/case,这个方法更长,验证在最后一行。在第二个中,我在第一行进行验证,而不是 switch/case 我声明了带有月份名称的表。
当我想到 KISS 和 DRY 原则时,哪个更好?
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");
}
}
或者也许这个?
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];
}
肥皂起泡泡
繁花不似锦
慕村225694
倚天杖
相关分类