简体   繁体   English

“==0”与“<1”的偏好

[英]Preference for “==0” vs. “<1”

I've written a method in Java to determine whether a given year is a leap year or not.我在 Java 中编写了一个方法来确定给定年份是否为闰年。 Here's the method as written:这是写的方法:

public static boolean isLeapYear (int year) {
        return year <= 9999 && year > 0 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

However, I noticed that IntelliJ originally corrected my redundant logic by replacing all of the instances of "== 0" with "< 1".但是,我注意到 IntelliJ 最初通过将“== 0”的所有实例替换为“< 1”来纠正我的冗余逻辑。 I've since changed them back to "==0" in the above example.在上面的例子中,我已经把它们改回了“==0”。

Is there some preference for one over the other in terms of code simplicity or clarity?就代码的简单性或清晰度而言,是否有某种偏好? It seems like the simpler version is the "equals 0" as it is more precise than simply "less than 1."似乎更简单的版本是“等于 0”,因为它比简单的“小于 1”更精确。

Not sure if there's some convention on this, or if there's a reason why you'd prefer to use <1 over ==0 in any given case.不确定是否对此有一些约定,或者是否有原因在任何给定情况下您更愿意使用 <1 而不是 ==0。

Thanks!谢谢!

Clarity is your guiding principle here: Go with == 0 and != 0 .清晰是您的指导原则:Go with == 0 and != 0

The two options are effectively interchangeable, because in your case the remainder can't be less than zero, however == 0 and != 0 are easier to read, and much closer to their natural langauge meaning of "has a remainder of zero" etc, and moreover it is the industry convention.这两个选项实际上可以互换,因为在您的情况下,余数不能小于零,但是== 0!= 0更容易阅读,并且更接近它们的自然语言含义“余数为零”等等,而且是行业惯例。

There is no "performance" difference.没有“性能”差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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