Search code examples
refactoringcoderush

Flatten conditional as a refactoring


Consider:

if (something) {
    // Code...
}

With CodeRush installed it recommended doing:

if (!something) {
    return;
}
// Code...

Could someone explain how this is better? Surely there is no benefit what so ever.


Solution

  • Isolated, as you've presented it - no benefit. But mark4o is right on: it's less nesting, which becomes very clear if you look at even, say a 4-level nesting:

    public void foo() {
        if (a)
            if (b)
                if (c)
                    if (d)
                        doSomething();
    }
    

    versus

    public void foo() {
        if (!a)
            return;
        if (!b)
            return;
        if (!c)
            return;
        if (!d)
            return;
        doSomething();
    }
    

    early returns like this improve readability.