Skip to content

Prefer to keep logic simple (was "Prefer shallow nesting of conditions") #4

@peno2

Description

@peno2

I suggest to add a guideline on "using guard clause" to simplify conditions.
This is a guideline present in for example mongodb's "Server Code Style", there named "Return Early".
See: https://github.com/mongodb/mongo/wiki/Server-Code-Style#return-early

Her comes a version which is a bit more worked through and more suitable as an actual guideline.
Comments are welcome!


Prefer shallow nesting of conditions. This usually makes the code easier to follow. It also makes the intent clearer.
Strive to place the essential code at outermost scope, unless this obscures intent.

Use a guard-clause to take care of exceptional cases and return early.

// Deep nesting, avoid if possible.
void foo() {
    ...
    if (x) {
        computeImportantThings(x);
    }
}

// Not so good either. Now an early return, but a redundant else.
void foo() {
    ...
    if (!x) {
        return;
    }
    else {
        computeImportantThings(x);
    }
}

// Good. Shallow nesting, early return, no redundant else and 
// important computation at outermost scope.
void foo() {
    ...
    if (!x)
        return;

    computeImportantThings(x);
}

Another example:

// Not so good. Unnecessary nesting of if-clauses.
void foo() {
    ...
    if(x) {
        if (y) {
             computeImportantThings(x);
        }
    }
}

// Suggested rewrite: shallow nesting, early return and the essential code at outermost scope.
void foo() {
    ...
    if (!(x && y))
        return;

    computeImportantThings(x);
}

Enforcement:

  • A tool can flag redundant else.

See also:
NR.2

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rnr-single-return

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions