所以我有一個函數,格式化日期以強制給定枚舉DateType {CURRENT,START,END} 什麼是最好的方式來處理返回值與使用switch語句的情況用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");
}
拋出錯誤時拋出或返回null
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語句中處理
如果你有一個不應該發生的情況,我會使用一個AssertionError。 – 2010-04-02 17:41:22
Thanks AssertionError比IllegalArgumentException更有意義 – Greg 2010-04-02 18:12:03