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"?
The JavaScript switch statement can contain return statements if it is present inside a function.
The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed. The case statements and the default statement can occur in any order in the switch statement.
The statements in a switch continue to execute as long as the condition at the top of the switch remains true.
The only way you could usefully have code after a "return" is if the "return" statement is conditional. This isn't great coding style, you're creating code where there are 2+ ways to exit. When you need to debug it you'll find it more challenging to put in flags and "what happened when we exited" and so forth.
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;
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