适时打破单入口单出口

断断续续看书学习中,今天看的一段还是很有感触的。

遵循单入口单出口的原则,在面对分支的时候时常会写出层层嵌套的代码(我就写过好多嵌套的,鄙视一下自己)

double getPayAmount(){
    double result;
    if (_isDead) result = deadAmount();
    else {
        if (_isSeparated) result = separatedAmount();
        else {
            if (_isRetried) result = retiredAmount();
            else result = normalPayAmount();
        }        
    }
    return result;
}

不再固守单入口单出口的原则,提前通知函数返回,看起来代码逻辑更清晰了。

double getPayAmount(){
    if (_isDead)        return deadAmount();
    if (_isSeparated)   return separatedAmount();
    if (_isRetried)     return retiredAmount();
    return normalPayAmount();
}

References

  • Refactoring: Improving the Design of Existing Code > Section 9.5: Replace Nested Conditional with Guard Clauses

评论

《 “适时打破单入口单出口” 》 有 2 条评论

  1. Ray Chow 的头像

    ❗ 这个原则太纠结了,还要弄多个标识变量。我向来是能return就return绝不弄什么while( flag == 0); 之类的东西=。=

    1. 流年 的头像
      流年

      @Ray Chow 单出口的好处在于想看返回的是什么,直接看最后就知道了。