[英]Is there any cleaner way to write multiple if-statements in Java
I have an if-else structure in Java as follow: 我在Java中有一个if-else结构,如下所示:
if (A || B || C){
if (A){
//Do something
}
if (B){
//Do something
}
if (C){
//Do something
}
} else {
//Do something
}
I want to know if there is any cleaner and easier way to replace this? 我想知道是否有更清洁,更简单的方法来替换它?
If A,B and C are conditions which are expensive to evaluate, you could use an additional flag to make sure they are only evaluated once: 如果A,B和C是评估成本高的条件,则可以使用额外的标志来确保它们仅被评估一次:
boolean found = false;
if (A) {
//Do something
found = true;
}
if (B){
//Do something
found = true;
}
if (C){
//Do something
found = true;
}
if (!found) {
//Do something
}
Otherwise (ie if they are not expensive to evaluate), I'd keep your current conditions. 否则(即如果它们评价起来并不昂贵),我会保持现状。
Yes. 是。
if (A) {
// do A
}
if (B) {
// do B
}
if (C) {
// do C
}
if (! (A || B || C)) {
// do "neither A or B or C"
}
Whilst I think what you have is fine, you could do it like this: 虽然我认为你有什么是好的,你可以这样做:
boolean d = false;
if (d |= A) { ... }
if (d |= B) { ... }
if (d |= C) { ... }
if (!d) {
// What to do if A..C are all false.
}
This will set d
to true if any of the conditions are matched ( d
is for "did something"). 如果任何条件匹配,则将d
设置为true( d
代表“做某事”)。
Just one more possible solution: 还有一个可能的解决方案:
public class ABC {
private static final Logger log = LoggerFactory.getLogger(ABC.class);
@Test
public void abc() {
boolean A = true;
boolean B = false;
boolean C = true;
boolean abcProcessed = false;
abcProcessed |= process(A, () -> {
// Do something for A
log.debug("A");
});
abcProcessed |= process(B, () -> {
// Do something for B
log.debug("B");
});
abcProcessed |= process(C, () -> {
// Do something for B
log.debug("C");
});
if (!abcProcessed) {
// Do something for !(A||B||C)
log.debug("!(A||B||C)");
}
}
private boolean process(boolean flag, DoSomethingInterface doSomethingInterface) {
// check condition
if (flag) {
// execute code specific for condition
doSomethingInterface.doSomething();
// return true (processed)
return true;
}
// return false (not processed)
return false;
}
public interface DoSomethingInterface {
// code specific for condition
void doSomething();
}
}
An idea is to move condition checking and related code to separate method. 一个想法是将条件检查和相关代码移动到单独的方法。
I think you should use else if conditions: 我认为你应该使用其他条件:
if(A){
}else if(B){
}else if(C){
}else if(D){
}
But, if you have many conditions like A,B,C etc it feels that something wrong with logic of your program 但是,如果你有许多条件,比如A,B,C等,那么你觉得你的程序逻辑有问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.