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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public void SomeMethod(string args) { if (args != null) var something = args.Something; if (something != null) { var someResult = DoSomethingWithSomething(something); if (someResult != null) { IGotMyResult(someResult); } } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
public void SomeMethod(string args) { if (args == null) return; var something = args.Something; if (something == null) return; var someResult = DoSomethingWithSomething(something); if (someResult == null) return; IGotMyResult(someResult); } |
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 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 was appointed the title of Sitecore Technical MVP in 2014 and has been re-appointed the title every year since then.
- Web |
- More Posts
Hear, hear
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 🙂