[導入]如何消除if else
這是一位同學的回帖,感覺可以單獨拿出來說說,原文: 我們現在在做一個項目,我負責整改以前開發過的代碼,可業務方法里的IF()ELSE{}語句特別長,看的都頭痛,請問您有什么好辦法能避免少些判斷語句嗎? 消除if
else的方法有很多,要區分不同的情況。根本上解決這個問題的途徑是參閱Martin Fowler的大作《重構》 給出兩個常見的方法: 1,用鍵值對格式的配置文件代替if 舉例:獲取數據庫驅動類名 final int CURRENT_DB = 0; String driver = ""; if (CURRENT_DB==0) driver="com.mysql.jdbc.Driver"; if (CURRENT_DB==1) driver="com.microsoft..."; if (CURRENT_DB==2) driver="sun.jdbc.odbc..."; 可以采用配置文件簡化,假設有如下的配置文件 DRIVER =
com.mysql.jdbc.Driver URL =
jdbc:mysql://localhost:3306 Then you
can use java.util.Properties load the configuration file, read the value simply be method get(key). 2,Use Design Pattern : Strategy(策略模式), Factory and State may the problem 例子可見《深入淺出設計模式》 |
文章來源: http://underwind.javaeye.com/blog/63129