I talked about refactoring large areas of code in my previous post: Refactoring with Color. It’s easy to make hand-wavey statements like “write shorter, simpler methods”, which is good guidance, but not necessarily that helpful. “Early return” or “early exit” has long been one of the most frequent comment I make on pull requests, and is one of my favorite refactoring tools. My team jokes that it’s the only comment I make.
For whatever reason, when we’re all taught if/else structures, the else almost always exist. However, when you can return from the function at the end of the if statement, there’s no need for the else statement at all.
I stumbled upon this post earlier this month and the graphic used to describe the benefits of early return are spot on. I also really liked how the author refers to the unnecessary nesting as “exhausting your mental stack”.
Example without early return:
Example with early return:
Visit the original article. Don’t worry about all the talk about “tail call optimization”. But look at how much shorter and easier to read the code is in his examples.
I am relieved when I find code in our codebase that follows this patterns. It ends up being a very straightforward and easy to read validation checks. Reducing the mental overhead of any particular piece of code helps us to understand the bigger picture better.
I also find that early returns works really well with TDD! You can Red/Green easily using this technique, and I find that once you get comfortable with it, it becomes the your default way to implement a method with lots of conditions to check.
Happy Holidays everyone!