3

I often write code such as the following

bool myFunct (...)
{
     if (something)
     {
          return false; 
     }         

     // .... more code ....

}

The alternative is

bool myFunct (...)
{
     if (something)
     {
          return false; 
     }         
     else
     {
          // .... more code ....
     }

}

Of course, that else block is unnecessary, because the early return means that reaching the else statement in the first place is the equivalent of being inside it. Then there's the fact that, to make the compiler happy, I often have to change the structure of the 2nd implementation to

bool myFunct (...)
{
     bool retval = true;
     if (something)
     {
          retval = false; 
     }         
     else
     {
          // .... more code ....
     }
     return retval;    
}

which is extra code and looks stupid. My question is, what do the governing authorities and priests say about this type of situation?

Lily Carter
  • 163
  • 1
  • 1
  • 5

4 Answers4

2

Of course. You're basically writing a guard condition that will stop you trying to perform unnecessary logic. It's fine.

Like many things, it's personal preference, but I prefer to see code written like your second example for simple cases, and the third example for more complex cases. That doesn't mean any are wrong, though.

ZombieSheep
  • 28,629
  • 10
  • 64
  • 112
2

Not only it is OK, it is even encouraged in Spartan Programming. According to Spartan Programming - shorter and simpler code is better, and you achive it (among other ways) by fast terminations and avoiding else statements when possible

Under minimizing use of control:

(2) Simplifying conditionals with early return.

(4) Simplifying logic of iteration with early exits (via return, continue and break statements).

P.S. It seems @Jeff Atwood also likes the spartan programming way

amit
  • 166,614
  • 24
  • 210
  • 314
0

There's nothing technically wrong with having an else clause for an if clause that does not terminate naturally (e.g., has a return or throw statement), it's just useless.

Several style guidelines argue against it (and several IDE and analysis tools may produce warnings to support these guidelines), but ultimately, it's just a preference.

Mureinik
  • 252,575
  • 45
  • 248
  • 283
0

The 2nd example looks fine to me because, if the code in the first statement is updated like below, it'll prevent unexpected behavior :

bool myFunct (...)
{
     if (something)
     {
          // ... stuff 
          if (something_else) return false; 
     }         
     else
     {
          // .... more code ....
     }

}
jazzytomato
  • 6,316
  • 2
  • 27
  • 41