1. 程式人生 > 實用技巧 >減少你的程式碼巢狀,讓你的程式碼可讀性大大提升

減少你的程式碼巢狀,讓你的程式碼可讀性大大提升

正常很多人寫程式碼會使用這樣的邏輯寫if程式碼也很符合當時的邏輯

例如:

if (true) {
    if (true) {
        if (true) {
            if (true) {
                if (true) {
                    if (true) {
                        
                    }
                }
            }
        }
    }
}

寫的時候一時爽,回頭維護像迷宮。看得第一眼都就頭大。

可讀性是真的差。

我們要如何讓他變得好些?我們碰到這樣的情況使用衛語句的方式處理。

public void doSomething(DomainA a) {
    if (a == null) {
        return ; //log some errorA
    }
    if (a.getB() == null) {
        return ; //log some errorB
    }
    if (!(a.getB().getC instanceof DomainC)) {
        return ;//log some errorC
    }
    assignAction;
    otherAction
    doSomethingA();
    doSomethingB();
    doSomthingC();
}

更為複雜的邏輯功能可以使用某些設計方式來解決。

可以看看這篇文章:https://www.jianshu.com/p/57c065b124c4