|
|
|
|
|
by brundolf
1898 days ago
|
|
Unpopular opinion: I think early-returns make code less readable if you don't put the rest of the function in an else clause. You lose visual parallelism, and suddenly instead of following a tree down to a series of leaves where every leaf terminates, you have to have the full context to know whether or not a line of code may not execute in some cases. For example: function foo(x) {
if (x == null) {
return null;
}
x += 2;
return x;
}
I can't just look at "x += 2;" and know whether or not it's conditionalized. I have to have the full context including the early-return, and then reason about the control flow from there. Whereas: function foo(x) {
if (x == null) {
return null;
} else {
x += 2;
return x;
}
}
Here I can tell just from the else-block that this is one possibility which will execute if the other one does not, and vice-versa. Their indentation is the same, cementing their relationship. If I want to know whether this block will execute I need only look at the if()'s, not their contents. |
|
That is, I don't think it matters too much whether you do:
or as they both accomplish the same major benefit of the pattern.The real thing it's helping to avoid is accidentally creating something like this:
which can quickly get very hard to reason about without in more complex cases.