Skip to content

Instantly share code, notes, and snippets.

@nboutin
Last active February 18, 2023 15:26
Show Gist options
  • Select an option

  • Save nboutin/9418bc7452145fa577de5a0a551273a3 to your computer and use it in GitHub Desktop.

Select an option

Save nboutin/9418bc7452145fa577de5a0a551273a3 to your computer and use it in GitHub Desktop.

Revisions

  1. nboutin revised this gist Feb 18, 2023. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion solve_if-else_indentation_hell.cpp
    Original file line number Diff line number Diff line change
    @@ -27,7 +27,7 @@ void func()
    }

    // Multiple return in function not allowed
    // Convert if-else to sucess/failure boolean
    // Convert if-else to success/failure boolean
    void func()
    {
    bool success = section_1();
  2. nboutin created this gist Feb 18, 2023.
    65 changes: 65 additions & 0 deletions solve_if-else_indentation_hell.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,65 @@
    // Multiple level of nesting
    void func()
    {
    if (...) {
    if (...) {
    ...
    } else {
    if (...) {
    ...
    } else if (...) {
    ...
    } else {
    ...
    }
    }
    ...
    }
    }
    // Convert if-else to if-return
    void func()
    {
    if (!test()) {
    handle_failure();
    return false;
    }
    // do lots of work
    }

    // Multiple return in function not allowed
    // Convert if-else to sucess/failure boolean
    void func()
    {
    bool success = section_1();

    if (success) {
    success = section_2();
    }

    if (success) {
    success = section_3();
    }
    }

    // Shorter
    void func()
    {
    bool success = section_1();
    success = success && section_2();
    }

    // Shorter
    void func()
    {
    bool success = section_1();
    success &= section_2();
    }

    // In for-loop, convert if-else to if-continue
    for(...) {
    const T& element = *iter;

    if (!test(element))
    continue;
    ...
    }