Guard clauses for better “if” statements — Python

Readability needs to be key when writing complex functions

Ícaro
Lemon Code
Published in
2 min readAug 11, 2019

--

Photo by Nery, snippet made in @carbon_app
Photo by Nery, snippet from @carbon_app

Lots of things can make code hard to understand. Confusing variables, high coupling, unnecessary complexity, and many other that we see (and sometimes do) everyday.

Sometimes we can’t avoid functions that need lots of validations to make sure it can execute what it’s there for. You can see an example below:

That’s very simple but you can see that the nested if statements make a “stairs” effect in the code, increasing line width which can harm code readability and increase complexity (by having you need to “remember” all the previous conditions of each if).

Be careful to not stumble on those indentation levels

The Guard Clause pattern helps in these cases by “inverting” that way of thinking and rapidly returning false conditions and keeping the important code blocks (usually the longest) in the lowest indentation level possible.

We have increased the line count but it’s a valid trade-off for the code quality improvements that counter what we mentioned in the previous example.

Below is another example of before and after applying guard clauses:

All the source code shown and explained here (mixins, functions, examples, samples, etc.) is available in the GitHub repository below along with other helpful projects I’ve developed and wrote about. Feel free to check it out, use them in your own work and help me improve them with your feedback.

🍋 🍋 🍋

--

--