Which method of returning a bool from a switch statement is preferable? I understand this may be subjective, however I feel it is important to our profession to get input on best practices :).
public bool foo(param)
{
switch (param)
{
case 1:
if (something)
{
return true;
}
return false;
default:
return false;
}
}
- OR -
public bool foo(param)
{
bool flag = false;
switch (param)
{
case 1:
if (something)
{
flag = true;
}
break;
default:
break;
}
return flag;
}
The difference here is between single point of return and multiple points of return.
Generally, single point of return code tends to do a lot of bookkeeping (temporary variables, checking of those variables in loops), and can get hairy as the logic gets more complex. I've seen code that goes to great lengths to use a while (flag) ... flag = false;
pattern instead of a while (true) ... break;
pattern, and it is not fun to read.
I prefer multiple points of return since they return as early as possible (no extra work done) and don't require any locals to help keep track of the current return value. Also, I don't find them any harder to read than single point of return code.
There's a good disucssion of this on c2 (SingleFunctionExitPoint).
I've found that keeping methods as "functional" as possible is a good thing (I say "functional" here because I'm typically doing C# which, outside of LINQ, is not considered functional). By "functional", I mean that I try to avoid mutating state as much as possible. Introducing more state in the form of locals or members makes things more difficult to understand since you now have to take into consideration their values and you have to consider how those variables can be set (from another method, from another class, ...).
In general, state is evil, but sometimes it's a necessary evil.
This particular issue has some interesting conversation here on SO as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With