Nesting if statements

This post is not only about Sitecore development it is valid for any code written in almost any language.

It is about making code easier to read. The post is somewhat subjective but I hope that all developers with an IQ higher than 80 will agree.

Back in the days when I learned to write code I could end up writing something  like this:

But what I was doing back then was actually turning things upside down, writing “stay with me” instead of saying no right away, making the code less readable for other developers.

Today I would always write the same piece of code like this:

The point being, STOP nesting if statements.

If a condition is not met then exit right away, don’t write “if condition met then do something” rather write “if condition not met then return” –  just exit, otherwise your method has to much responsibility.

This is kind of a continuation of my post about exiting fast in pipeline processors which I wrote some months ago here.

I hope all readers of this post will listen and change their approach if they are still nesting if statements. It is just an unnecessary waste of white spaces.

Anders Laub

Anders Laub Christoffersen

Anders has been working with Sitecore for over a decade and has in this time been the lead developer and architect on several large scale enterprise solutions all around the world. Anders has been nominated a Sitecore Technical MVP three years in a row for 2014, 2015 and 2016. Anders is now working as a Sr. Solutions Architect at Sitecore in Copenhagen.

2 thoughts on “Nesting if statements

  1. It’s interesting to see an opinion on this topic. The question of early returns comes frequently to my mind, especially with ReSharper at hands, but I haven’t discussed it or seen a lot of comments around. I’m also incligned to prefer the suggested practice.

    Here are some additional sources of comments:
    http://confluence.jetbrains.com/display/ReSharper/Invert+%27if%27+to+reduce+nesting

    http://stackoverflow.com/questions/268132/invert-if-statement-to-reduce-nesting

    http://peterkellner.net/2009/10/18/refactor-csharp-if-resharper/

    And no, JetBrains don’t pay me to promote their products, I’m just a fanboy :)

    PS Sorry for the multiple posts but couldn’t beat the html parser of this blog :)

Leave a Reply

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

*
*
Website