Get those Guards up

I often find code which have several nested conditionals like this:

public void FunctionWithoutGuardClauses(Person person)

{

    if (person != null)

    {

        if (person.Phone != null)

        {

            person.Phone.Call();

        }

        else

        {

            throw new ArgumentNullException();

        }

    }

    else

    {

        throw new ArgumentNullException();

    }

}knight4

According to Steve McConnell in Code Complete 2 it is just fine with regards to putting the most probable clause first. But it is also an anti-pattern in this case; arrow code. With even more nesting it gets worse, and it starts to get nightmarish to follow the possible execution paths.

Oh, and see how I blatantly disregard the Law of Demeter!

Introducing Guard Clauses

A guard clause is a conditional which constitutes our first line of defence in our methods. It can break control flow in an elegant matter, so the only thing left to follow is the valid execution path.

There is also nothing wrong with more than one return path in our methods, as long as it is as clean as it gets with guard clauses. Atwood seems to think so as well, so I’m really home safe here ;-p

So lets see how the above code can be refactored with guard clauses:

public void FunctionWithGuardClauses(Person person)

{

    if (person == null || person.Phone == null)

        throw new ArgumentNullException();

 

    person.Phone.Call();

}

So what are you waiting for, get those guards up and tear those nested nightmares apart!

Leave a comment