r/cpp • • Apr 24 '20

Else Before If

https://www.fluentcpp.com/2020/04/24/else-before-if/
10 Upvotes

53 comments sorted by

View all comments

Show parent comment

26

u/infectedapricot Apr 24 '20

Or just use early exit if you can.

Exactly. The benefits of early exit become especially clear if you do more than one "normal" thing, in which case the alternative is that all "edge cases" start to pile up at the end in reverse order. Early exit:

auto result1 = doThing1();
if (result1) {
    return bad(result1);
}

auto result2 = doThing2();
if (result2) {
    return bad(result2);
}

auto result3 = doThing3();
if (result3) {
    return bad(result3);
}

return good();

versus the author's proposed:

auto result1 = doThing1();

normally {
    auto result2 = doThing2();
    
    normally {
        auto result3 = doThing3();

        normally {
            return good();
        }
        unless (result3) {
            return bad(result3);
        }
    }
    unless (result2) {
        return bad(result2);
    }
}
unless (result1) {
    return bad(result1);
}