When is it appropriate to use a fall-through (classic) switch statement? Is such usage recommended and encouraged or should it be avoided at all costs?
|
|
Here's an example where it would be useful.
This sort of thing (where one case includes the other) is rather rare, I think, which is why some newer languages either don't allow fallover or require special syntax for it. |
|||||||||||
|
|
I use them when certain functionality has to be applied for more than one value. For example, say you had an object with a property called operationCode. If the code equals 1, 2, 3 or 4, you want to startOperationX(). If it's 5 or 6, you want to startOperationY() and 7 you startOperationZ(). Why have 7 complete cases with functionality and breaks when you can use fall-throughs? I think it's completely valid in certain situations, especially if it avoids 100 if-else statements. =) |
|||||||||||||||||
|
|
I've used them occasionally, I think its always appropriate usage - but only when included with the appropriate comment. |
|||
|
|
|
It depends on:
The two main problems associated with letting one case fall through to the next are:
Some places explicitly prohibit falling through. If you don't work at such a place, and if you're comfortable with the practice, and if breaking the code in question won't cause any real suffering, then it might not be the worst thing in the world. If you do it, though, be sure to put an attention-grabbing comment nearby to warn those who come later (including the future you). |
|||
|
|
|
Fall-through cases are perfectly fine. I often find that an enumeration is used in lots of places, and that when you don't need to differentiate some cases it is easier to use fall-through logic. For example (note the explanatory comments):
I find this kind of use perfectly acceptable. |
|||
|
|
|
If I feel a need to go from one case to another (rare, admittedly), I prefer to be very explicit and Because falling thru is so uncommon, and very easy to overlook while reading code, I feel it is appropriate to be explicit - and a goto, even if it's to a case, should stand out like a sore thumb. It also helps avoid bugs that may occur when case statements are reordered. |
|||
|
|

