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!