Why you should reduce nesting blocks in your code, with practical refactoring tips

Brook Novak
2 min readAug 4, 2021

--

Deeply nested statements is a nasty code smell. AKA “hadouken indentation”.

Here is an example of deep nesting: (i.e. many levels or nesting in a single method):

Note another key code smells in play: violation of single responsibility principle (a car start method handling both manuals and automatic transmissions). The complicated flow as ended up with many deep code block with if statements. Lots of annoying horizontal scrolling. Lots of tracking else blocks, and tracking what conditions allow you to get into a specific block. Can we do better? Hell yes!!!!!!

Lets apply some code perfumes to get rid of those smells …

As you can see, the nesting in the first example makes the code very unreadable, and difficult to track all the combinations of branching conditions within a method block. Ultimately this imposes a high amount of cognitive effort on the reader to follow the code. Refactoring away nesting makes it so much more maintainable.

Relationship with long method smell, and extract method refactoring.

Nesting also prevents us from breaking up long methods into smaller methods (using the beloved extract method refactor). Often, heavy use of nesting is a symptom of the method doing too much.

So, this means refactoring away nested statements also paves the way towards easy “extract method” refactoring (to avoid single responsibility principles violations)

How to fix nesting?

So what refactorings were applied in the car example above? Let me introduce to the super handy refactoring.. “invert if” …

“Invert if” refactoring

“Invert if” is one of the most handy, common refactoring catalog items. A lot of IDE tools like Visual studio, visual code, resharper will all have tooling to automatically do this for you, going as far as suggesting them for you.

Tips with using this technique

  • deal with “exceptional”, or non-happy path (or non-standard path) cases first.
  • look out for “early exits” / “short circuits”

Replace nested conditional checks with Guard statements

Often you may have argument checks at the start of a method using if statements and maybe some nesting. You can replace these with guard statements instead.

Guard statements might be offered to you as a first class citizen in the language (e.g in swift).

Other languages, like C# might have 3rd party guard libs available (like Dawn Guard, or Guard.NET). Or you can roll your own if you are weary about dependencies like XUnit did.

--

--

Brook Novak

Clean coding TDD and BDD Zealot. Full stack dotnet dev.