简体   繁体   中英

java ternary operator can be replaced with Math.max call

I have the following code delay = (delay>200)? delay: 200; delay = (delay>200)? delay: 200;
Java issues a warning message Can be replaced with 'Math.max' call for this.
Here I see that Math.max(a, b) is actually the same as (a > b)? a: b (a > b)? a: b so ternary operator is not worse than Math.max
So why Java issues this warning message if there are no advantages replacing the ternary operator by Math.max method call?

I doubt that this is a real compiler warning, probably some IDE inspection/warning.

Nonetheless, you are correct, there are no hard technical reasons to prefer one over the other.

But: from the point of a human reader, using Math.max() has one major advantage: it is easier to read and understand. That simple.

Besides: do not duplicate code unless you have to.

Always remember: you write your code for your human readers. Compilers accept anything that is syntactically correct. But for your human readers, there is a difference between a condition and an assignment vs a very telling "take the maximum of two numbers".

Math.max(a, b) is more readable than the tenary statement because:

  • the value 200 does not need to be repeated.
  • there is no need to write and understand >

In general, the ternary is more powerful because it lets you do things like this:

    delay = (delay>200) ? 200 : delay;
    delay = (delay<200) ? delay : 200;
    delay = (delay>200) ? delay: 300;

The reader of your code needs to understand which of those things you are actually doing. It takes time to parse it and understand it is a simple max() .

The max shows your intention more clearly.

In addition to the existing answers, there can be a performance advantage if the lower limit (in your case, 200) is not a constant but a derived value:

delay = (delay > readLimitFromFile()) ? delay : readLimitFromFile();

This could end up doing 2 expensive disk-read operations, when one operation would be sufficient. Using Math.max:

delay = Math.max(delay, readLimitFromFile());

would use only one disk-read operation.

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