I am not an if-nester, I am the kind of developer who don’t like conditions getting deeply nested. At work i am the one who sees some nested code and try to promote removing the nesting, There are acceptable levels, sure - but I still don’t like it.

Level 1

This is fine.

if (loggedIn) {

}
Level 2

Still acceptable.

if (loggedIn) {
  if (authorized) {

  }
}

Level 3

Nope. This is where it gets ugly.

if (loggedIn) {
    if (authorized) {
        if (someCondition) {

        }
    }
}

There are developers who can go to level 3 and still feel nothing. But man, I just can’t look at this mess. Its just start to hit my OCD. I know it works but it lacks the elegance and on top of that, its hard to read and even harder to debug.

On the other hand, all of this gets sorted if you use guard clauses.

What is a guard clause?

Its just reversing the condition and returning early. So the true condition can be executed below that. Lets try some hands on to flatten all three levels above mentioned.

if (!loggedIn) {
return;
}

if (!authorized) {
return;
}

if (!someCondition) {
return;
}

See how using guard clauses turns deep nesting into a clean linear flow. From the time i see it in some online tutorial i have been using it and it has become my motto to promote it.

Let me know your thoughts.