20 July 2022

C++ 核心指南目录

“Avoid unnecessary condition nesting”

理由

浅层嵌套的代码更容易理解;代码意图更清晰。努力用尽量少的代码条件分支判断实现程序。

例子

利用保卫语句(guard-clause),让代码早返回或早退出。

// Bad: Deep nesting
void foo() {
    ...
    if (x) {
        computeImportantThings(x);
    }
}

// Bad: Still a redundant else.
void foo() {
    ...
    if (!x) {
        return;
    }
    else {
        computeImportantThings(x);
    }
}
// Good: Early return, no redundant else
void foo() {
    ...
    if (!x)
        return;

    computeImportantThings(x);
}

例子

// Bad: Unnecessary nesting of conditions
void foo() {
    ...
    if (x) {
        if (y) {
            computeImportantThings(x);
        }
    }
}
// Good: Merge conditions + return early
void foo() {
    ...
    if (!(x && y))
        return;

    computeImportantThings(x);
}

强化

  • 标记多余的 else。
  • 标记函数体只是简单的通过条件语句包含了代码块。