I'm using Java 6.
Suppose I have an enum with 6 values, ordered A to F. About 4 of the values were handled the same. I could write it like this.
switch (whichType) {
case A:
case B:
case C:
case D:
return task();
case E:
return someothertask();
case F:
return anothersomeothertask();
}
Or like this.
switch (whichType) {
case E:
return someothertask();
case F:
return anothersomeothertask();
default:
return task();
}
Null values will never reach this switch.
In terms of conciseness and clarity, the second approach is better. In terms of being explicit, I think the first approach is better.
Are there any other pros/cons of each approach?
Also, this simple question risks being a duplicate, but I tried and couldn't find it asked anywhere yet. I apologize if I haven't searched it good enough.
Both are fine if that enum is absolutely, positively fixed at six values forever. Otherwise, think about what a possible seventh value for the enum might be. If E and F are the only two possible outliers with respect to this switch
logic and any other value would fall in the same bucket as A through D, go ahead and use the default
. Otherwise, you're safer to have a case
per value.
Suppose someone adds a value to the enumeration?
In some code I've got, there's this sort of construct:
switch(mediaType) {
case typeA:
case typeB:
case typeC:
DoGeneric();
break;
case TypeD:
DoSpecial();
break;
}
And the reason for that is so that if someone adds another possibility to the enumeration, it won't compile until you've looked at the places the enumeration is used and decided what needs to be done at that point. No chance of missing one and having a difficult-to-track-down bug.
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