Kata

Early exit

Early exit, also called early return, is a useful technique for reducing nesting and making your code more linear. If the main part of your function is wrapped in many different conditions, it can get buried in the middle of all that logic, making the whole function harder to read and understand.

The solution is to reverse your thinking: you're not using conditions to say when your code should run, you're using them to say when it shouldn't. Those kind of conditions are called guards, and the nice thing about them is that you just read them in order. If you pass all the guards, congratulations! You're now allowed to run through the rest of the function in peace.

Be warned, though, early exits can be used for evil as well as good. Scattering them around at different points throughout a large function is a recipe for confusing and unexpected bugss.

Early exit

Nested conditions