# Java code refactoring example ## 例子1.(重構前) 依照考績決定動作 ``` public static String Grade(String grade) { String result = ""; switch (grade) { case "優": result = "出國去玩"; break; case "甲": result = "買台電腦犒賞自己"; break; case "乙": result = "去逛街放鬆心情"; break; case "丙": result = "準備翻報紙找工作"; break; default: result = "輸入錯誤,請重新輸入一次!"; } return result; } ``` ## 例子1(用多型取代) ``` abstract class Grade{ abstract String getResult(String grade); } class Excellent extends Grade{ String getResult(String grade) { return "出國去玩"; } } class GradeA extends Grade{ String getResult(String grade) { return "買台電腦犒賞自己"; } } class GradeB extends Grade{ String getResult(String grade) { return "去逛街放鬆心情"; } } class GradeC extends Grade{ String getResult(String grade) { return "準備翻報紙找工作"; } } ``` ## 例子1(用hashmap取代條件句) ``` import java.io.IOException; import java.util.HashMap; public class Evaluate { public static void main(String[] args) { HashMap<String, String> m = buildMap(); String grade = "優"; try { System.out.println(m.get(grade)); } catch(Exception e){ System.out.println(e); } } public static HashMap<String, String> buildMap() { HashMap<String, String> map = new HashMap<String, String>(); map.put("優", "出國去玩"); map.put("甲", "買台電腦犒賞自己"); map.put("乙", "去逛街放鬆心情"); map.put("丙", "準備翻報紙找工作"); return map; } } ``` ## 例子1(用enum搭配switch) ``` import java.io.IOException; enum SomeCase{ 優{ public String getResult() { return "出國去玩"; } }, 甲{ public String getResult() { return "買台電腦犒賞自己"; } }, 乙{ public String getResult() { return "去逛街放鬆心情"; } }, 丙{ public String getResult() { return "準備翻報紙找工作"; } }; public abstract String getResult(); } public class Evaluate { public static void main(String[] args) { SomeCase ex = SomeCase.乙; switch (ex) { case 優: case 甲: case 乙: case 丙: System.out.println(ex.getResult()); break; default: throw new IllegalArgumentException("輸入錯誤,請重新輸入一次!"); } } } ``` ## 參考來源 * 書籍 : 最新 Java 8 程式語言(第四版) 作者: 施威銘研究室 範例頁數 : 5-20