YES! traditionally More than one return from a function is a code smell.
Nowadays there are widely used practices that are common enough to be recognised as an exception to the rule
- early return guard clauses
- exceptions
However, I believe the (highly underrated) second answer is really talking about the combination of the second exit point and the setting of the flag.
The combination requires the early exit AND further checking of the variable after the loop completes.
For instance a loop with a return when a condition is met
foreach(var x in list)
{
if(condition(x)) { break;}
//whatever
}
return z;
Is fairly obvious and a simple optimisation.
But a loop which sets variables AND has multiple returns quickly becomes non obvious and potentially buggy
var z
foreach(var x in list)
{
if(condition(x)) { z = something }
if(condition2(x)) { break;}
}
if(z==something)
{
//will this code execute?
}
return z;
Analogous to a function with side effects, or a global variable.
The same is true for multiple returns
//some code
if(condition)
{
return x
}
//more code possibly not executed
if(condition2)
{
return y
}
//more code possibly not executed
return z;
OR
foreach(x in list)
{
if(condition)
{
flag = y;
}
if(condition2 && flag)
{
return b;
}
if(condition3)
{
return c;
}
}
Scanning the code you cant tell which return will be hit. But you can see that there is more than one exit. This is the "code smell" which tells you you need to look more closely at this function as it could do something unexpected.
Because we are "triggered" by this code smell its best to avoid it, even in the simple cases by simplifying to a while loop or map, to remove the second return/break
while(x.next && !condition(x))
{
//whatever
}
list.Where(x=>condition(x)).select(//whatever)
When we scan this code we know that it can only do a single thing because there is only a single exit point. To get past it the conditions stated at the start must have been met. We might not care how, all we know is we can continue reading the code knowing what the state of the variables must be.