Java switch case - 默认与显式枚举 [英] Java switch case - default vs explicit enumeration
问题描述
我使用的是 Java 6.
I'm using Java 6.
假设我有一个包含 6 个值的枚举,按 A 到 F 的顺序排列.大约 4 个值的处理方式相同.我可以这样写.
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();
}
或者像这样.
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.
推荐答案
如果枚举是绝对的,永远固定在六个值,那么两者都很好.否则,请考虑枚举的可能的第七个值.如果 E 和 F 是与此 switch
逻辑相关的仅有的两个可能的异常值,并且任何其他值都将与 A 到 D 落入同一桶中,请继续使用 default
.否则,每个值都有一个 case
会更安全.
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.
这篇关于Java switch case - 默认与显式枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!