|
|
|
|
|
by fenomas
609 days ago
|
|
It definitely depends, but personally I find early returns to be a bit of an antipattern IF they're based on business logic. If a function has lots of ifs, you can glance at the nesting to see which ones affect the line you want to edit, and ignore the others. But if the function has lots of returns, you have to check every one before a given line in order to know what constraints are true at that point. OTOH early returns are great for anything the type checker knows about: function foo(msg: 'OK' | 'ERR') {
// ...
if (msg === 'ERR') return someValue
// ...
}
Doing that is hugely cleaner than branching, and there's no added complexity to the developer since tooling can easily tell you what values `msg` can have at any given point in the function. |
|
Only if all the cases return! Only then is it obvious that you have independent cases. E.g. suppose we have three Boolean inputs x, y, z and want to do something for each binary combination:
How would this look with early returns? One obvious way: (Let's ignore that we can just calculate the output with some bit twiddling; that's not the point).Early return can be very clear, if we can bear repeatedly testing some conditions.