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.
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”