9 種方法來解決掉那些“煩人”的 if else

1.使用 return

我們使用 return 去掉多餘的 else,實現代碼如下。
優化前代碼:

if ("java".equals(str)) {
    // 業務代碼......
} else {
    return;
}

優化後代碼:

if (!"java".equals(str)) {
    return;
}

// 業務代碼…
這樣看起來就會舒服很多,雖然相差只有一行代碼,但真正的高手和普通人之間的差距就是從這一行行代碼中體現出來的。
「勿以善小而不爲,勿以惡小而爲之」「千里之堤,潰於蟻穴」,說的都是同樣的道理。

2.使用 Map

使用 Map 數組,把相關的判斷信息,定義爲元素信息可以直接避免 if else 判斷,實現代碼如下。
優化前代碼:

if (t == 1) {
    type = "name";
} else if (t == 2) {
    type = "id";
} else if (t == 3) {
    type = "mobile";
}

我們先定義一個 Map 數組,把相關判斷信息存儲起來:

Map<Integer, String> typeMap = new HashMap<>();
typeMap.put(1, "name");
typeMap.put(2, "id");
typeMap.put(3, "mobile");

之前的判斷語句可以使用以下一行代碼代替了:

type = typeMap.get(t);

3.使用三元運算符

三元運算符也叫三元表達式或者三目運算符/表達式,不過代表的都是一個意思,優化代碼如下。
優化前代碼:

Integer score = 81;
if (score > 80) {
    score = 100;
} else {
    score = 60;
}

優化後代碼:

score = score > 80 ? 100 : 60;

4.合併條件表達式

在項目中有些邏輯判斷是可以通過梳理和歸納,變更爲更簡單易懂的邏輯判斷代碼,如下所示。
優化前代碼:

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";
}

5.使用枚舉

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;

6.使用 Optional

從 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+ 才行。

7.梳理優化判斷邏輯

和第 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; 

我們需要儘量把表達式中的包含關係改爲平行關係,這樣代碼可讀性更高,邏輯更清晰。

8.使用多態

繼承、封裝和多態是 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();

有人可能會說,這樣反而讓代碼更加複雜了,此可謂“殺雞焉用宰牛刀”的典型範例了。這裏作者只是提供一種實現思路和提供了一些簡易版的代碼,以供開發者在實際開發中,多一種思路和選擇,具體用不用需要根據實際情況來定了。靈活變通,舉一反三,纔是開發的上乘心法。

9.選擇性的使用 switch

很多人都搞不懂 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;
    }
}

作者:Java中文社羣
鏈接:https://juejin.im/post/5e9fee616fb9a03c4d411175
來源:掘金
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章