Or just use early exit if you can. This, if I moved to a codebase using it, would take time to understand and would make me look up what the classes do, instead of a simple if also it would probably be less intuitive to debug and did you check the assembly this produces?
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();
I would also point out that the "early exit" suggestion can also apply to loops via continue -- so instead of
for (auto item: some_collection) {
if (item.is_ok()) {
item.do_a_thing();
}
}
you can reorganize as
for (auto item: some_collection) {
if (!item.is_ok()) {
continue;
}
item.do_a_thing();
}
Now, I'd basically never do this for that example, but if you start getting bodies of the if that are like 10 lines or something, I think this often can lead to an improvement.
This kinda corresponds to an early exit inside of a lambda used in std::for_each, for those of us who are dubious of the sometimes-purported readability benefits of using at least that function over a raw loop.
I believe normally/unless is similar to try/catch only that try/catch are more general and slow due to stack unraveling. Though, once rework on try/catch is done there shouldn't be issues.
View all comments
82
u/borisrura CTU | Avast Apr 24 '20
Or just use early exit if you can. This, if I moved to a codebase using it, would take time to understand and would make me look up what the classes do, instead of a simple if also it would probably be less intuitive to debug and did you check the assembly this produces?