2
if (condition1)
{
    return;
}
else
{
   ...
   if (condition2)
   {
       return;
   }
   else
   {
       ...
   }
}

vs

if (condition1) return; ... if (condition2) return; ...

I generally include the else even when if returns, but I keep seeing it omitted. I realize it's not required, so is it actually clearer to leave else out? Is there a stylistic consensus?

If there are a lot of if/else clauses following the nested structure above, will there be any significant differences in execution time?

user2455117
  • 153
  • 2
  • 10
  • What if your condition is false? – Bibhas Debnath Mar 27 '14 at 20:07
  • I forgot a return in the dummy code. Is that what you meant? – user2455117 Mar 27 '14 at 20:09
  • I'm not sure how returning in if block is related to removing the else block. You return if your condition is true. But what if your condition is false? Are your else blocks empty? – Bibhas Debnath Mar 27 '14 at 20:11
  • No...? The alternative would be `if (condition1) return; ... if (condition2) return; ...` If that's unclear without the linebreaks, I added it to the original question. – user2455117 Mar 27 '14 at 20:13
  • This question has been asked to death. Generally it’s better to avoid deep nesting. Except in pathological cases, there is certainly no difference in the compiled code, as they have identical control flow graphs. – Jon Purdy Mar 27 '14 at 20:17

5 Answers5

3

If you follow the "Single Return Principle" (see this question and others), then you will never return from within an if block.

If you're not, then in my opinion it's a matter of personal preference, but also depends on the situation. Basically I try to do whatever is most clear. Generally I do include the else because it is more clear, but sometimes I won't; here's an example of where it seems wasteful (and not any clearer) to include the else clause(s):

bool test_three_things( /*some input...*/ )
{
    if ( /*first test...*/ )
      return false;

    if ( /*second test...*/ )
      return false;

    if ( /*third test...*/ )
      return false;

    return true;
}

In this case it's clear what's going on. However if I'm writing a single if in the context of a larger block of code, I generally include the else.

Community
  • 1
  • 1
aldo
  • 2,927
  • 21
  • 36
0

This is really a personal opinion based question. There is no right answer. Everybody does it their own preferred way. My preferred way is to check for invalid cases as early as possible. That way the code stays less indented and more readable. I usually use this for validating input parameters. So my preferred way is -

if (condition1)
{
    // this is invalid case for me, return
    return;
}

if (condition2)
{
    // this is also invalid case for me, return
    return;
}

// My actual work with the valid cases goes here

Following a really deep if...else pattern doesn't have any significant improvement over this.

Bibhas Debnath
  • 14,559
  • 17
  • 68
  • 96
0

Take this way

You go to the store with money in your pocket to buy only chocolate less than 100$ otherwise you will buy clothes.So if and else relaxes restrictions. you can buy between the two. On the other hand if you go to market to buy only chocolates then you have few choices so only if means more restrictions. Based on this example you can decide what you want in your code.

Naseer
  • 4,041
  • 9
  • 36
  • 72
0

It depends. A little.

For trivial cases, I'll often keep an else for obvious parallelism:

def foo(arg1, arg2):
    if condition:
        return arg1
    else:
        return arg2

But for anything that gets remotely complicated, I'll drop the else, and generally advise others do the same. This is because it's really difficult to follow a function like this:

def foo():
    if cond1:
        # ten lines here
        return value
    else:
        if cond2:
            # another ten lines
            return value
        else:
            if cond3:
                # ten more lines
                return value

            # ...a couple dozen lines here...

    return value

Say I want to refactor this function, or some code that uses it, and I want to know how exactly the return value is computed because someone forgot to write documentation. The first thing I see is three separate ifs all with a bunch of code in them, and now it looks like there are eight different combinations of things that might have happened to value, and who knows how many paths to each return and I sigh and take a swig of vodka and go to figure out what they all are.

Worse, imagine if each of those if blocks only conditionally does a return.

On the other hand, this is pretty easy to follow even with many more conditions:

def foo():
    if cond1:
        # ten lines here
        return value

    if cond2:
         # another ten lines
        return value

    if cond3:
        # ten more lines
        return value

    # ...a couple dozen lines here...

    return value

How many ways can this go? Four, and they're clearly intended to be mutually exclusive, and the returns even line up visually.

Nested blocks read like exponential complexity. Sequential blocks read like a series of steps, which is more like what you intend to convey.

Ultimately I think keeping your returns outdented as far as possible is a good compromise with the spirit of the Single Return Principle, which I've otherwise never bothered to follow.

And yes, I've refactored code like this :)

Eevee
  • 47,412
  • 11
  • 95
  • 127
-1

Look, as return kills the current function in which it's called, all code below the return statement will be ignored.

The only code that executes after a return statement it's the code located inside a finally, like this:

try{
    if(condition == true)
    {
        return;
    }
}
finally{
    //Code here will run too
}
Ivan Verges
  • 595
  • 3
  • 10
  • 25