[J2SE] enum應用問題
在寫一些Util的時候 在想到底是用enum好還是不要好
一般Util傳入參數 值可能是限定某些值
一種做法是宣告一些final static String .....
但是可能問題是 使用Util的人 不傳你這宣告好的參數 他傳自訂String "xxxx"
所以你有可能會收到例外的值
另一種做法用enum
但是我覺得enum也有問題
如果使用者參數傳遞 ENUM.valueOf("xxx")
一樣會有例外值 並且會拋出Exception
變成使用Util的人必須自己處理Exception
第三種變通的做法
就是仍然宣告ENUM 但是參數宣告仍為基本型態
但是ENUM用在Util裡面檢查用
我想了想 是哪種設計方法好呢?
以下附上範例討論的Util
和可能情況code
可能呼叫情況:
public static void main(String a[]) {
String url = "http://www.asiafm.com.tw/";
//call changeProtocol(String url, String prot)
System.out.println( URLUtil.changeProtocol(url,"http") );
System.out.println( URLUtil.changeProtocol(url,PROTOCOL.http.toString()) );
System.out.println( URLUtil.changeProtocol(url,"httpxx") );//參數值不在遇期內
//call changeProtocol(String url, PROTOCOL prot)
System.out.println( URLUtil.changeProtocol(url,PROTOCOL.http) );
System.out.println( URLUtil.changeProtocol(url,PROTOCOL.valueOf("httpxx")) );
//參數值不在遇期內 , 會有IllegalArgumentException
//參數值不在遇期內 ,必須自己處理IllegalArgumentException
try{
System.out.println( URLUtil.changeProtocol(url,PROTOCOL.valueOf("httpxx")) );
}catch(IllegalArgumentException e){}
範例Util:
enum PROTOCOL {http,https,ftp,ftps}
public class URLUtil {
/*
* ex1:
* String url = "http://www.asiafm.com.tw/";
* URLUtil.changeProtocol(url,"http")
*/
public static String changeProtocol(String url, String prot) {
//valid url
if (ValueUtil.isStringEmpty(url)) {
return "";
}
//valid protocol
try{
PROTOCOL.valueOf(prot);
}catch(IllegalArgumentException e){
return url;
}
return prot + url.substring(url.indexOf("://"), url.length());
}
public static String changeProtocol(String url, PROTOCOL prot) {
//valid url
if (ValueUtil.isStringEmpty(url)) {
return "";
}
return prot + url.substring(url.indexOf("://"), url.length());
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 60.250.192.34
→
03/03 15:55, , 1F
03/03 15:55, 1F
→
03/03 17:05, , 2F
03/03 17:05, 2F
→
03/03 17:52, , 3F
03/03 17:52, 3F
推
03/04 02:14, , 4F
03/04 02:14, 4F
→
03/04 10:50, , 5F
03/04 10:50, 5F
→
03/04 20:33, , 6F
03/04 20:33, 6F
討論串 (同標題文章)