|
|
|
|
|
by kbenson
1894 days ago
|
|
I think your version isn't really as different as it seems to some. To me, the essential bit of early return is that you handle cases that eliminate the work first. That is, it's less about singular if statements separating the rest of the body of the function than it is clearly short circuiting the code as early as is clearly possible. That is, I don't think it matters too much whether you do: function div(x,y) {
if (y == null) {
return null;
}
if (y == 0) {
return null;
}
return x/y;
}
or function div(x,y) {
if (y == null) {
return null;
} else if (y == 0) {
return null;
} else {
return x/y;
}
}
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: function div(x,y) {
if (y != null) {
if (y != 0) {
return x/y;
} else {
return null;
}
} else {
return null;
}
}
which can quickly get very hard to reason about without in more complex cases. |
|
In practice, in C-like languages, I tend to see the "else-less" version which is why I brought it up