1

Possible Duplicate:
Is it bad style to use return at the beginning of a function to avoid doing unnecessary work?

Is there any other consideration besides personal taste on returning early or using an if enclosing a long method like in:

foo(bool bar)
{
    if(!bar)
    {
       return; 
    }

    ...
}

vs

foo(bool bar)
{ 
    if (bar)
    {
       ...

       return;
    }
}
Community
  • 1
  • 1
Mauricio Quintana
  • 391
  • 1
  • 4
  • 13
  • Yes it similar, although in this example there is no necessary work on either, I believe it is only a matter of style, but I might be missing some consideration when deciding going one way or another. also it might be matter of what is your mantra; "Fail early" vs "Single exit point" – Mauricio Quintana Nov 25 '12 at 21:49
  • Also as I just found out, the Mcabe Cyclomatic complexity should be taken into account, in the sense that the style with less complexity should be favored – Mauricio Quintana Nov 26 '12 at 17:39

1 Answers1

2

Using

foo(bool bar)
{ 
    if (bar)
    {
       ...

       return;
    }
}

can get a bit hairy if you have multiple conditions to test within the if-block. Such as:

foo(bool bar)
{ 
    if (bar)
    {
       ...
        if (baz)
        {
            ...
            if (barbaz)
            {
                ...
            }
        }
        return;
    }
}

In this case, if you were to return early, you would reduce a lot of nesting.

foo (bool bar)
{
    if (!bar) return;
    ...
    if (!baz) return;
    ...
    if (!barBaz) return;
    ...
    return;
}

In fact, as a ReSharper user, I use the code reformatting sugestion "Invert if to reduce nesting" quite often. In the end I think it's a preference thing, but to me it seems a bit more readable when there aren't too many nested ifs to match braces for.

armen.shimoon
  • 6,303
  • 24
  • 32