2 ms·
There are two issues here. First, why use switch instead of a series of if-else, apart from compile-time completeness checks? Second, why include an empty defau
by mtinkerhess 13y ago
There are two issues here. First, why use switch instead of a series of if-else, apart from compile-time completeness checks? Second, why include an empty default statement in a switch, apart from preventing compile-time completeness checks?
If a series of if-else statements can be rewritten as a switch statement, it will almost always be slightly more concise as a switch statement, and a more semantically correct representation of the logic.
Including an empty default statement come down to a matter of preference, but a pretty good argument for including it is that it favors the explicit over the implicit. It's better to be clear to other programmers that yes, you did intend to have nothing occur if the switched value didn't have a matching case. If you intend to handle all cases, you can put "assert false" or similar in the default case to be explicit about it. I can see that one going either way with enums, though, if you get a compile-time error when forgetting to handle a value (it's been too long since I've worked in Java to remember how it handles that).