Let's say I have code in C with approximately this structure:
switch (something)
{
case 0:
return "blah";
break;
case 1:
case 4:
return "foo";
break;
case 2:
case 3:
return "bar";
break;
default:
return "foobar";
break;
}
Now obviously, the "break"s are not necessary for the code to run correctly, but it sort of looks like bad practice if I don't put them there to me.
What do you think? Is it fine to remove them? Or would you keep them for increased "correctness"?
Remove them. It's idiomatic to return from
case
statements, and it's "unreachable code" noise otherwise.Personally I would remove the returns and keep the breaks. I would use the switch statement to assign a value to a variable. Then return that variable after the switch statement.
Though this is an arguable point I've always felt that good design and encapsulation means one way in and one way out. It is much easier to guarantee the logic and you don't accidentally miss cleanup code based on the cyclomatic complexity of your function.
One exception: Returning early is okay if a bad parameter is detected at the beginning of a function--before any resources are acquired.
I would say remove them and define a default: branch.
I personally tend to lose the
break
s. Possibly one source of this habit is from programming window procedures for Windows apps:I personally find this approach a lot simpler, succinct and flexible than declaring a return variable set by each handler, then returning it at the end. Given this approach, the
break
s are redundant and therefore should go - they serve no useful purpose (syntactically or IMO visually) and only bloat the code.Keep the breaks - you're less likely to run into trouble if/when you edit the code later if the breaks are already in place.
Having said that, it's considered by many (including me) to be bad practice to return from the middle of a function. Ideally a function should have one entry point and one exit point.
I say remove them. If your code is so unreadable that you need to stick breaks in there 'to be on the safe side', you should reconsider your coding style :)
Also I've always prefered not to mix breaks and returns in the switch statement, but rather stick with one of them.