I’m wondering where a switch statement of this style should be changed to an if else statement.
switch (foo) // foo is an enumerated type
{
case barOne:
if (blahOne)
{
DoFunction(//parameters specific to barOne);
break;
}
case barTwo:
if (blahTwo)
{
DoFunction(//parameters specific to barTwo);
break;
}
//etc.
default:
// Whatever happens if none of the case's conditionals are met
}
Basically fall through is happening unless a condition is met for one of the cases. The cases are very similar, differing only in what needs to be checked for and what needs to be passed, which is why I used a switch statement.
Would it be better to use if else if? Otherwise, is it clear enough to stay, but unclear enough to warrant a comment about the fallthrough? Polymorphism is also always an option, but it seems like overkill to me.
It seems like this might do strange things in some cases. What if foo == bar1, and blahOne is false, but blahTwo is true? Then you’ll fall through and call the function under the foo == bar2 case, even though foo doesn’t equal bar2.
That might be unexpected in practice, but if it ever did occur it might be tough to debug. I’d vote for an if else in this case, because the flow is simpler.
Of course, if the intention is that blahTwo can be evaluated even though foo != barTwo, then the switch might be the best way to do it, but I’d definitely be in favor of some explanatory comments in that case.