如何以更好的方式表示以下 if else
条件?
if ((!StringUtils.isEmpty(A) && !StringUtils.isEmpty(B)) {
System.out.println("Case 1");
} else if ((!StringUtils.isEmpty(A) && StringUtils.isEmpty(B)) {
System.out.println("Case 2");
} else if ((StringUtils.isEmpty(A) && !StringUtils.isEmpty(B)) {
System.out.println("Case 3");
} else if ((StringUtils.isEmpty(A) && StringUtils.isEmpty(B)) {
System.out.println("Case 4");
} else {
System.out.println("End");
}
最佳答案
假设 Case 1
和 Case 4
不应该有相同的条件,从而消除了 End
的可能性,你可以这样做:
if (StringUtils.isEmpty(A)) {
if (StringUtils.isEmpty(B)) {
System.out.println("Case 4");
} else {
System.out.println("Case 3");
}
} else {
if (StringUtils.isEmpty(B)) {
System.out.println("Case 2");
} else {
System.out.println("Case 1");
}
}
或者你可以使用一个 switch 语句,稍微算一下:
switch ((StringUtils.isEmpty(A) ? 2 : 0) | (StringUtils.isEmpty(B) ? 1 : 0)) {
case 0: // !empty(A) & !empty(B)
System.out.println("Case 1");
break;
case 1: // !empty(A) & empty(B)
System.out.println("Case 2");
break;
case 2: // empty(A) & !empty(B)
System.out.println("Case 3");
break;
default: // empty(A) & empty(B)
System.out.println("Case 4");
}
关于java - If else 冗余代码简化为更简单的形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46679573/