Should I use return/continue statement instead of if-else?
Solution 1
The compiler will almost certainly generate the same code. Even if it didn't, the difference will be probably irrelevant. Hence, the relevant argument is certainly how people would read it.
Therefore the question is how similar "//do some stuff" and "do other stuff" are. If they are conceptually similar, use if/else. If they're conceptually different, use continue/return.
Solution 2
My personal approach of choosing one is that if the body of the if
part is very short (3 or 4 lines maximum), it makes sense to use the return/continue
variant. If the body is long, it's harder to keep track of the control flow so I choose the else
version.
As a result, normally, this approach limits the usage of return/continue
style to skip some data and avoid further processing rather than process this using one of the following methods (which is better suited by if/else
).
Solution 3
The code would be more readable if termination criteria are handled first. I always prefer, checking for conditions that require a break or return rather than those that would need lengthy code execution. I prefer:
if (termination condn)
return;
// code
// code
to
if (success condn)
{
// code
// code
}
else
return;
This makes reading and understanding the code easier.
Solution 4
It depends a little on how long the branches are. The use of return/continue that you describe is good if the initial if
check is short, and the body is long. If both if
and else
parts are long, I would extract them to separate functions.
I recommend reading Code Complete, it discusses things like this a lot.
Solution 5
The glib answer is that it all depends.
My general feeling is that if condition
is a rare, guard (e.g. check for null) or error condition then I tend to use return
or continue
If it's an expected case then I tend to use your first approach.
Notice, however, that I said "tend". The boundary between these to conditions is vague and subject to change depending on the project and who I'm working with.
sharptooth
Updated on July 09, 2022Comments
-
sharptooth almost 2 years
In C, C++ and C# when using a condition inside a function or loop statement it's possible to use a continue or return statement as early as possible and get rid of the else branch of an if-else statement. For example:
while( loopCondition ) { if( innerCondition ) { //do some stuff } else { //do other stuff } }
becomes
while( loopCondition ) { if( innerCondition ) { //do some stuff continue; } //do other stuff }
and
void function() { if( condition ) { //do some stuff } else { //do other stuff } }
becomes
void function() { if( condition ) { //do some stuff return; } //do other stuff }
The "after" variant may be more readable if the if-else branches are long because this alteration eliminates indenting for the else branch.
Is such using of return/continue a good idea? Are there any possible maintenance or readability problems?