英文:
How to improve switch case that returns true/false or throw an exception?
问题
给定以下代码:
private boolean isBlahTrue(final BigDecimal status) {
switch (status.intValue()) {
case 1:
case 2:
case 3:
return true;
case 5:
case 6:
case 7:
return false;
default:
throw new MyAppRuntimeException("状态未知!");
}
}
我的问题是:这种做法是好的还是坏的?
逻辑是:
1, 2, 3 --> true
5, 6, 7 --> false
但是,有人可能认为使用简单的IF语句也可以完成,比如
if (1,2,3) {true}, else {false}
但是,这样的话我就无法检查状态是否为4(这必须引发异常)。
我尝试过一些解决方案,比如使用contains,但是代码没有改善。
有什么想法可以尝试吗?
英文:
Given the following code:
private boolean isBlahTrue(final BigDecimal status) {
switch (status.intValue()) {
case 1:
case 2:
case 3:
return true;
case 5:
case 6:
case 7:
return false;
default:
throw new MyAppRuntimeException("Status unknown!");
}
}
My question is: Is this good or bad practice?
Logic is:
1, 2, 3 --> true
5, 6, 7 --> false
But anyway one could think about that a simple IF would do the stuff too, like
if (1,2,3) {true}, else {false}
.
But then I would not check if the status is e.g. 4 (which must lead to an exception).
I tried some solutions, like contains, but the code doesn't improve.
Any ideas that I could try?
答案1
得分: 0
我建议在这种情况下使用一个 Map。
类似于
Map<Integer, Boolean> statusChecker = new HashMap<>();
statusChecker.put(1, true);
statusChecker.put(2, true);
// ...
statusChecker.put(5, false);
// ...
现在你可以进行检查
if (!statusChecker.containsKey(status)) {
throw new RuntimeException("无效状态");
} else {
return statusChecker.get(status);
}
英文:
I would suggest using a Map in this case.
something like
Map<Integer, Boolean> statusChecker = new HashMap<>();
statusChecker.put(1, true);
statusChecker.put(2, true);
...
statusChecker.put(5, false);
...
Now you can do the checking
if(!statusChecker.contains(status)) {
throw RuntimeException("invalid status");
} else {
return statusChecker.get(status);
}
答案2
得分: 0
已有的部分没有问题。但是,如果您正在使用Java 12或更高版本,您可以利用Java 12引入的开关表达式:
private boolean isBlahTrue(final BigDecimal status) {
return switch (status.intValue()){
case 1, 2, 3 -> true;
case 5, 6, 7 -> false;
default -> throw new MyAppRuntimeException("状态未知!");
};
}
英文:
There is nothing wrong with what you already have. But if you are using Java12 or higher you can make use of the switch expressions introduced in Java 12:
private boolean isBlahTrue(final BigDecimal status) {
return switch (status.intValue()){
case 1, 2, 3 -> true;
case 5, 6, 7 -> false;
default -> throw new MyAppRuntimeException("Status unknown!");
};
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论