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
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
Otherwise (i.e. if they are not expensive to evaluate), I'd keep your current conditions.
归档时间: |
|
查看次数: |
144 次 |
最近记录: |