匿名数组索引而不是 switch 语句?
在Java中,我发现下面的代码比相应的笨重的switch
语句更干净、更容易维护:
try {
selectedObj = new Object[] {
objA,
objB,
objC,
objD,
}[unvalidatedIndex];
} catch (ArrayIndexOutOfBoundsException e) {
selectedObj = objA;
}
与
switch (unvalidatedIndex) {
case 0:
selectedObj = objA;
break;
case 1:
selectedObj = objB;
break;
case 2:
selectedObj = objC;
break;
case 3:
selectedObj = objD;
break;
default:
selectedObj = objA;
}
Is the前者被认为是可接受的做法相反吗?我知道这不是最有效的,因为它涉及分配数组和捕获异常。当 unvalidatedIndex
超出范围时(尽管异常已处理),是否会导致不良情况?
如果可能的话,你会推荐一些更干净的东西吗?
In Java, I find the following code much cleaner and easier to maintain than the corresponding bulky switch
statement:
try {
selectedObj = new Object[] {
objA,
objB,
objC,
objD,
}[unvalidatedIndex];
} catch (ArrayIndexOutOfBoundsException e) {
selectedObj = objA;
}
opposed to
switch (unvalidatedIndex) {
case 0:
selectedObj = objA;
break;
case 1:
selectedObj = objB;
break;
case 2:
selectedObj = objC;
break;
case 3:
selectedObj = objD;
break;
default:
selectedObj = objA;
}
Is the former considered an acceptable practice? I am aware that it's not the most efficient one as it involves allocating an array and catching an exception. Would it cause something undesirable when unvalidatedIndex
is out of range (although the exception is handled)?
If possible, would you suggest something cleaner?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你的第一个方法很好。
不过,最好先检查一下索引:
Your first approach is fine.
However, it is better to check the index first:
这不是一种可接受的做法。异常用于错误处理,而不是程序流程。
异常也非常慢。
It is not an acceptable practice. Exceptions are for errors handling, not for program flow.
Also exceptions are VERY SLOW.
两者都是反模式。只需亲自测试范围成员资格的索引即可。在许多实际情况下可能有一种使用
enum
的方法。Both are antipatterns. Just test the index for range membership yourself. There might be a way to use an
enum
in many actual cases.就我个人而言,尽管我毫不怀疑有些人会不同意,但我会这样做:
它干净、紧凑、高效,而且非常容易理解。
我会犹豫是否包含
case 0
,即default
情况。Personally, though I have no doubt some will disagree, I would do:
It's clean, compact, efficient, and really easy to understand.
I would hesitate to include the
case 0
, that being thedefault
case.怎么样
How about
列表来自 Guava。
Lists comes from Guava.