[英]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;
delay = (delay>200)? delay: 200;
Java
issues a warning message Can be replaced with 'Math.max' call
for this. Java
发出警告消息Can be replaced with 'Math.max' call
。
Here I see that Math.max(a, b)
is actually the same as (a > b)? a: b
在这里我看到Math.max(a, b)
实际上与(a > b)? a: b
(a > b)? a: b
so ternary operator is not worse than Math.max
(a > b)? a: b
所以三元运算符不比Math.max
差
So why Java
issues this warning message if there are no advantages replacing the ternary operator by Math.max
method call?那么,如果通过Math.max
方法调用替换三元运算符没有优势,为什么Java
发出此警告消息?
I doubt that this is a real compiler warning, probably some IDE inspection/warning.我怀疑这是一个真正的编译器警告,可能是一些 IDE 检查/警告。
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.但是:从人类读者的角度来看,使用Math.max()
有一个主要优势:更容易阅读和理解。 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: Math.max(a, b)
比 tenary 语句更具可读性,因为:
200
does not need to be repeated.值200
不需要重复。>
没必要写明白>
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()
.解析它并理解它是一个简单的max()
需要时间。
The max
shows your intention more clearly. max
更清楚地显示了您的意图。
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:除了现有答案之外,如果下限(在您的情况下为 200)不是常数而是派生值,则可能会带来性能优势:
delay = (delay > readLimitFromFile()) ? delay : readLimitFromFile();
This could end up doing 2 expensive disk-read operations, when one operation would be sufficient.当一个操作就足够时,这最终可能会执行 2 次昂贵的磁盘读取操作。 Using Math.max:使用 Math.max:
delay = Math.max(delay, readLimitFromFile());
would use only one disk-read operation.将只使用一次磁盘读取操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.