所以我有一个函数可以格式化日期以强制给定的枚举 DateType{CURRENT, START, END}
在使用 switch 语句的情况下处理返回值的最佳方法是什么
public static String format(Date date, DateType datetype) {
..validation checks
switch(datetype){
case CURRENT:{
return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss");
}
...
default:throw new ("Something strange happend");
}
}
或者在最后抛出异常
public static String format(Date date, DateType datetype) {
..validation checks
switch(datetype){
case CURRENT:{
return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss");
}
...
}
//It will never reach here, just to make compiler happy
throw new IllegalArgumentException("Something strange happend");
}
或返回空值
public static String format(Date date, DateType datetype) {
..validation checks
switch(datetype){
case CURRENT:{
return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss");
}
...
}
return null;
}
这里的最佳实践是什么?此外,所有枚举值都将在 case 语句中处理
抛出异常,因为这是一个例外情况。
并把它扔到外面switch
,它会更具可读性。否则听起来就像“默认情况是例外”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)