In this post we are going to argue for ‘guard clauses’ and ‘returning early’. Let’s look at some of the common arguments for this.
Early Returns are better than Nested Conditionals
Early Returns let you get negative use cases out of the way to focus and simplify the main use case.
Early Returns are a good place to throw exceptions.
Better than Nested Conditionals.
I think the benefits here are quite obvious. Let’s take a look at some nested conditionals.
Compared with:
The latter is obviously much cleaner. Returning early can be used to prevent excess nesting of code blocks.
Get negative use cases out of the way early
So here is a pretty good use case for early returns in the wild in FirefoxLite. Another way it may be written is to wrap the whole function in an if test that will check for the positive use case. I’ve seen code like that and have even written code like that, but the early return here is easily better.
Early Returns are a good place to throw exceptions.
See the “Throw Early Catch Late” principle.
This is pretty solid. Since you are probably using early returns to validate input (backend or frontend), throwing an exception in an early return is the soonest you can throw it.