简体   繁体   中英

How can I simplify my if-else statement in java?

In my code I have a method size(MyData) that returns size of data - it can be 0 or greater. I also have a flag exclude that can be true or false . The point of my algorithm is to do some operation on data based on its size and the value of the flag.

  • If the size is greater than 0, I want to do operation on data.

  • If the size is 0, then I need to check the value of the flag excluded . In that case, if the flag excluded is set to true, I don't want to do operation on data. But if the flag is set to false, I need to do operation on data.

This is my algorithm so far:

int numberOfKids = size(MyData); //this can be 0 or greater
if (numberOfKids != 0) {
    //do operation
}
else {
    if (!exclude) {
        //do operation
    }
}

is there a better way of writing this algorithm? Thanks!

Assuming it's the same operation:

int numberOfKids = size(MyData); //this can be 0 or greater
if (numberOfKids != 0 || !exclude) {
    //do operation
}

The || comparison works by evaluating the left side, and if it is true, the right side is skipped. But if the left side is false, then the right side is evaluated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM