Switch statement with returns -- code correctness [closed] Switch statement with returns -- code correctness [closed] c c

Switch statement with returns -- code correctness [closed]


Remove the break statements. They aren't needed and perhaps some compilers will issue "Unreachable code" warnings.


I would take a different tack entirely. Don't RETURN in the middle of the method/function. Instead, just put the return value in a local variable and send it at the end.

Personally, I find the following to be more readable:

String result = "";switch (something) {case 0:  result = "blah";  break;case 1:  result = "foo";  break;}return result;


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.