Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any cleaner way to write multiple if-statements in Java

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?

like image 319
Alex Wang Avatar asked Oct 31 '25 12:10

Alex Wang


1 Answers

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.

like image 183
Eran Avatar answered Nov 02 '25 02:11

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!