4 ms·
Each switch statement includes a default statement group, even if it contains no code. I've never understood this one: adding `default` just prevents the compi
by erichocean 13y ago
Each switch statement includes a default statement group, even if it contains no code.
I've never understood this one: adding `default` just prevents the compiler from telling you when you forgot to handle a particular case...in which case (heh), why use a switch statement at all? What are you buying over a series of if-else statements, other than possible code reuse due to the fall-through behavior?
- mhurron 13y ago> What are you buying over a series of if-else statement Code clarity. Depending on how and what you're doing in each case a switch statement can be easier to read than a whole series of if .. else blocks. And sometimes, given that they are equivalent, it's just a style choice on the part of the programmer.
- gohrt 13y agoThe example uses ints, for which I have never seen every case handled. For enums, the default case should be left out, since 'default' actually masks the missing case, as you note.
- mtinkerhess 13y agoThere 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).