简体   繁体   中英

How can I simplify this if statement?

Basically, I am doing a java program for school. The checkstyle program we are required to use is saying that I am not simplifying my if statement enough. Is there a better way to do this?

My code:

    if (check() == true)
    {
        return amount * 0.85;
    }
    else
    {
        return amount;
    }

No need to add == true when you're already working with a boolean

if (check()) {
...
}
else {
...
}

您可以使用三元运算符。

return check() ? amount * 0.85 : amount

Convert the boolean to an integer, then use that as an index int an array to get the value to multiply amount by, and you don't need an if or ternary operator:

return amount * (new double[] {1.0, 0.85}[Boolean.compare(check(), false)]);

I am kidding, don't downvote me please. This is the worst way I could come up with.

In seriousness, style checking programs mostly care about how complex your expressions are and how many potential branches there are (cyclomatic complexity), so remove the else , and don't compare true to true to get true , and that should be enough to make it happy.

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