I have an if-else structure in Java as follow:
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:
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 (i.e. if they are not expensive to evaluate), I'd keep your current conditions.
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