3 ms·
Personally, I find the first version easier to read since it makes the structure explicit. I.e. there are two blocks and you will execute one or the other. To
by harimau777 8y ago
Personally, I find the first version easier to read since it makes the structure explicit. I.e. there are two blocks and you will execute one or the other.
To me the second version makes it more difficult to differentiate the structure:
if (...) {
foo()
return ...
}
return bar()
from:
if (...) {
foo()
}
return bar()
I find that when I'm reading code I'm generally more interested in the overall structure than in the specific implementation details. Especially since if the first block was complicated enough to tax my cognitive overhead, then I would probably extract it into a function anyways.
- joshuamorton 8y agoThere's a reason the pattern is referred to as "exiting early". Another description might be using guards. Basically, you shouldn't do this if you're doing something complex Basically you can imagine each of the if statements being a "guard" against an condition that might cause you to exit early. This becomes much clearer if you have multiple such clauses, and add the mental note that each conditional should contain only a return statement with a single expression. function foo(bar) { if is_null(bar) { return TypeError } if !validate_input(bar) { return ValueError } if cached(bar) { return cache(bar) } // Added as a workaround for client XYZCorp since... if (bar == "A special value) { return "A special result" } return do_a_complex_thing_to(bar) } You could equivalently structure it as a bunch of else ifs, but there's no real reason to do it that way.