if else 是咱們寫代碼時,使用頻率最高的關鍵詞之一,然而有時過多的 if else 會讓咱們感到腦袋疼,例以下面這個僞代碼:
是否是很奔潰?雖然他是僞代碼,而且看起來也很誇張,但在現實中,當咱們無數次 review 別人代碼時,都會發現相似的場景,那麼咱們本文就來詳細聊聊,有沒有什麼方法可讓咱們避免來寫這麼多的 if else 呢?html
咱們本文提供了 9 種方法來解決掉那些「煩人」的 if else,一塊兒來看吧。java
咱們使用 return
去掉多餘的 else,實現代碼以下。編程
優化前代碼:數組
if ("java".equals(str)) { // 業務代碼...... } else { return; }
優化後代碼:ide
if (!"java".equals(str)) { return; } // 業務代碼......
這樣看起來就會舒服不少,雖然相差只有一行代碼,但真正的高手和普通人之間的差距就是從這一行行代碼中體現出來的。性能
「勿以善小而不爲,勿以惡小而爲之」「千里之堤,潰於蟻穴」,說的都是一樣的道理。優化
使用 Map 數組,把相關的判斷信息,定義爲元素信息能夠直接避免 if else 判斷,實現代碼以下。ui
優化前代碼:this
if (t == 1) { type = "name"; } else if (t == 2) { type = "id"; } else if (t == 3) { type = "mobile"; }
咱們先定義一個 Map 數組,把相關判斷信息存儲起來:.net
Map<Integer, String> typeMap = new HashMap<>(); typeMap.put(1, "name"); typeMap.put(2, "id"); typeMap.put(3, "mobile");
以前的判斷語句可使用如下一行代碼代替了:
type = typeMap.get(t);
三元運算符也叫三元表達式或者三目運算符/表達式,不過表明的都是一個意思,優化代碼以下。
優化前代碼:
Integer score = 81; if (score > 80) { score = 100; } else { score = 60; }
優化後代碼:
score = score > 80 ? 100 : 60;
在項目中有些邏輯判斷是能夠經過梳理和概括,變動爲更簡單易懂的邏輯判斷代碼,以下所示。
優化前代碼:
String city = "西安"; String area = "029"; String province = "陝西"; if ("西安".equals(city)) { return "xi'an"; } if ("029".equals(area)) { return "xi'an"; } if ("陝西".equals(province)){ return "xi'an"; }
優化後代碼:
if ("西安".equals(city) || "029".equals(area) || "陝西".equals(province)){ return "xi'an"; }
JDK 1.5 中引入了新的類型——枚舉(enum),咱們使用它能夠完成不少功能,例以下面這個。
優化前代碼:
Integer typeId = 0; String type = "Name"; if ("Name".equals(type)) { typeId = 1; } else if ("Age".equals(type)) { typeId = 2; } else if ("Address".equals(type)) { typeId = 3; }
優化時,咱們先來定義一個枚舉:
public enum TypeEnum { Name(1), Age(2), Address(3); public Integer typeId; TypeEnum(Integer typeId) { this.typeId = typeId; } }
以前的 if else 判斷就能夠被以下一行代碼所替代了:
typeId = TypeEnum.valueOf("Name").typeId;
從 JDK 1.8 開始引入 Optional 類,在 JDK 9 時對 Optional 類進行了改進,增長了 ifPresentOrElse() 方法,咱們能夠藉助它,來消除 if else 的判斷,使用以下。
優化前代碼:
String str = "java"; if (str == null) { System.out.println("Null"); } else { System.out.println(str); }
優化後代碼:
Optional<String> opt = Optional.of("java"); opt.ifPresentOrElse(v -> System.out.println(v), () -> System.out.println("Null"));
小貼士:注意運行版本,必須是 JDK 9+ 才行。
和第 4 點比較相似,咱們能夠經過分析 if else 的邏輯判斷語義,寫出更加易懂的代碼,例如如下這個嵌套判斷的優化。
優化前代碼:
// 年齡大於 18 if (age > 18) { // 工資大於 5000 if (salary > 5000) { // 是否漂亮 if (pretty == true) { return true; } } } return false;
優化後代碼:
if (age < 18) { return false; } if (salary < 5000) { return false; } return pretty;
咱們須要儘可能把表達式中的包含關係改成平行關係,這樣代碼可讀性更高,邏輯更清晰。
繼承、封裝和多態是 OOP(面向對象編程)的重要思想,本文咱們使用多態的思想,提供一種去除 if else 方法。
優化前代碼:
Integer typeId = 0; String type = "Name"; if ("Name".equals(type)) { typeId = 1; } else if ("Age".equals(type)) { typeId = 2; } else if ("Address".equals(type)) { typeId = 3; }
使用多態,咱們先定義一個接口,在接口中聲明一個公共返回 typeId
的方法,在添加三個子類分別實現這三個子類,實現代碼以下:
public interface IType { public Integer getType(); } public class Name implements IType { @Override public Integer getType() { return 1; } } public class Age implements IType { @Override public Integer getType() { return 2; } } public class Address implements IType { @Override public Integer getType() { return 3; } }
注意:爲了簡便咱們這裏把類和接口放到了一個代碼塊中,在實際開發中應該分別建立一個接口和三個類分別存儲。
此時,咱們以前的 if else 判斷就能夠改成以下代碼:
IType itype = (IType) Class.forName("com.example." + type).newInstance(); Integer typeId = itype.getType();
有人可能會說,這樣反而讓代碼更加複雜了,此可謂「殺雞焉用宰牛刀」的典型範例了。這裏做者只是提供一種實現思路和提供了一些簡易版的代碼,以供開發者在實際開發中,多一種思路和選擇,具體用不用須要根據實際狀況來定了。靈活變通,觸類旁通,纔是開發的上乘心法。
不少人都搞不懂 switch 和 if else 的使用場景,但在二者都能使用的狀況下,能夠儘可能使用 switch,由於 switch 在常量分支選擇時,switch 性能會比 if else 高。
if else 判斷代碼:
if ("add".equals(cmd)) { result = n1 + n2; } else if ("subtract".equals(cmd)) { result = n1 - n2; } else if ("multiply".equals(cmd)) { result = n1 * n2; } else if ("divide".equals(cmd)) { result = n1 / n2; } else if ("modulo".equals(cmd)) { result = n1 % n2; }
switch 代碼:
switch (cmd) { case "add": result = n1 + n2; break; case "subtract": result = n1 - n2; break; case "multiply": result = n1 * n2; break; case "divide": result = n1 / n2; break; case "modulo": result = n1 % n2; break; }
在 Java 14 可以使用 switch 代碼塊,實現代碼以下:
// java 14 switch (cmd) { case "add" -> { result = n1 + n2; } case "subtract" -> { result = n1 - n2; } case "multiply" -> { result = n1 * n2; } case "divide" -> { result = n1 / n2; } case "modulo" -> { result = n1 % n2; } }
業精於勤荒於嬉,行成於思毀於隨。編程是一門手藝,更是一種樂趣,哈佛最受歡迎的幸福課《幸福的方法》一書中寫到「讓咱們能感到快樂和幸福的方法,無非是全身心的投入到本身稍微努力一下才能完成的工做中去!」是啊,太簡單的事情一般沒法調動起咱們的興趣,而太難的工做又會讓咱們喪失信心,只有那些看似很難但稍微努力一點就能完成的事情,纔會給咱們帶來巨大的快樂。
原創不易,若是以爲本文對你有用,請隨手點擊一個「贊」,這是對做者最大的支持與尊重,謝謝你。
參考 & 鳴謝
https://www.tuicool.com/wx/2euqQvZ
http://www.blogjava.net/xzclog/archive/2006/10/16/75399.html