Using Guard Clauses to reduce nesting levels in our code

File-level namespaces in C# 10 will help us remove a level of nesting in our code. This is helpful but.. actually the real problem with nesting doesn’t come from a language constraint but rather often comes from our coding style….

.. I’m referring to having multiple levels of nested if conditionals in a method. This is perfectly valid code but IMHO it can be hard to understand. A pseudo code example is below. This kind of code is often referred to as arrow anti pattern code as we can see that the indentation forms an arrow.

An alternative to nested ifs is to use guard clauses. This is where we test our conditionals early and exit the method immediately if anything is in a bad state. As we’ve tested our conditionals early our ‘Happy Path’ code (eg. the main thing the method does) is not buried in lots of if and else blocks.

The example above (it’s JavaScript but its the same kind of idea for all languages) is from Álvaro Trigos Twitter. Note the example is actually missing the throw keyword so code should be throw new Error(… etc. but hopefully you still get the idea.

What do you think? IMHO the code on the right is a lot easier to read.

2 thoughts on “Using Guard Clauses to reduce nesting levels in our code”

Leave a Reply

Your email address will not be published. Required fields are marked *