所以我有一个函数可以格式化一个日期来强制给定的枚举 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 语句中处理
最佳答案
抛出异常,因为这是一个异常(exception)情况。
并且把它丢在switch
之外,这样可读性会更好。否则听起来像是“默认情况下是异常(exception)”。
关于java - 抛出异常与使用 switch 语句返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2567932/