How to represent the following if else
condition in a better way?
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");
}
Assuming Case 1
and Case 4
are not supposed to have the same condition, which eliminates the possibility of End
, you can do this:
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");
}
}
Or you can use a switch statement, with a little bit-math:
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With