Is a single return with boolean logic equivalent to guard clauses?

1k Views Asked by At

I'm working on a Boolean function in C/C++ that verifies multiple conditions (that are Boolean functions themselves) and only returns true if all of them are true.

Time ago I started using Guard Clauses instead of nested ifs, even though it required having multiple returns like follows:

bool foo(){
 //some initialization

 if( !condition_1() ){
  return false;
 }

 if( !condition_2() ){
  return false;
 }

 ...

 if( !condition_n() ){
  return false;
 }

 return true;
}

But now I'm asking my self if is it a good alternative to use only one return with Boolean logic, for example:

bool foo(){
 //some initialization
 return condition_1() && condition_2() && ... && condition_n() ;
}

I don't have any code to run after the guards and there are only a few of them, so the return statement is not that crowded and the code is not difficult to read. The idea is to avoid nested ifs and use only one exit point in my function.

I tested the code and it works fine, even if condition_1() makes some changes in condition_2(). So I understand that the guard clause code and this version are equivalent and the execution order is maintained form left to right. Is that correct? Are there any hidden differences that make the two versions not 100% equivalent?

Thanks!

2

There are 2 best solutions below

3
Guillaume D On

You new approach is good, depending if you want to do more than just concat bool operations, it could be useful for maintenance and readability to use a local.

bool foo(){
 //some initialization
 bool returnCondition = condition_1() &&
                        condition_2() && 
                        condition_3() && 
                        .... && 
                        condition_n();

 return returnCondition;
}

By the way, there is nothing such as the best option. Indeed, if your objective is code obfuscation, your first option is better than the 2nd.

3
Ahmed Yasen On

Technically the two methods you use are correct in case of the functions condition_n() is used only for checking.

But if you need to change something inside them based on a condition of something it will be a problem.

The Best Practice for writing a function body is as follows:

  • define the default return value
  • some processing
  • return the result

Let's rewrite the above function :

bool foo(){
//some initialization
  bool ret = true;

  if(condition_1() == false){
     ret = false;
  }
  else if(condition_2() == false){
     ret = false;
  }

  ...

  else if(condition_n() == false){
     ret = false;
  }

 return ret;
}