Clean Code: Nesting

This is the start of a series of posts about Clean Code. I’m going to pick some topics from my cheat sheets about Clean Code and Clean Test Driven Development and explain them in more details.

Today’s topic is

Nested code should be more specific or handle less probable scenarios than unnested code.

Let’s make an example:

public void DoMagic(int i)
{
    if (i < 0)
    {
        throw new ArgumentException(i, “i must not be negative”);
    }

    // do magic here
}

is better understandable than

public void DoMagic(int i)
{
    if (i >= 0)
    {
        // do magic here
        return;
    }

    throw new ArgumentException(i, “i must not be negative”);
}

I hope you agree. This is an obvious example because an exception should always be a special case.

But what about this example:

public void DoMagic(int i)
{
    if (i < 0)
    {
        // do magic for negative values here
        return;
    }

    // do normal magic here
}

versus

public void DoMagic(int i)
{
    if (i >= 0)
    {
        // do normal magic
        return;
    }

    // do magic for negative values here
}

versus

public void DoMagic(int i)
{
    if (i >= 0)
    {
        // do normal magic
    }
    else
    {
        // do magic for negative values here
    }
}

Which variant is the cleanest – the easiest to understand?

That depends on what how likely positive and negative values are in this do magic scenario.

If positive values are the normal case then I ‘d prefer the first variant. If negative values are the normal case then the second variant. Finally, if positive and negative values are equally important then the third variant.

You think, that’s overkill for a simple if statement?

Please take a moment and replace the simple if check in the sample above with some complex business rule. Then nesting the more special behavior will result in code that is far quicker to understand then randomly organized nesting.

About the author

Urs Enzler

Add comment

By Urs Enzler

Recent Posts