[英]Why does org.apache.commons.lang.BooleanUtils.isTrue(Boolean bool) use the ternary operator?
I F3'd into this for no particular reason, and was surprised to see this method implemented as follows: 我没有特别的原因对此进行过F3,并且惊讶地发现这种方法实现如下:
public static boolean isTrue(Boolean bool) {
if (bool == null) {
return false;
}
return bool.booleanValue() ? true : false;
}
Why not? 为什么不?
public static boolean isTrue(Boolean bool) {
if (bool == null) {
return false;
}
return bool.booleanValue();
}
It doesn't really matter, so I wondered is there some benefit to it? 这并不重要,所以我想知道它有什么好处吗? Readability is a weak enough argument, I consider this to be noise.
可读性是一个足够弱的论点,我认为这是噪音。 Unless there is some other benefit that I am missing.
除非我遗失了一些其他好处。
I can't find any justifiable reason. 我找不到任何合理的理由。
The API specification for Java says: Java的API规范说:
public boolean booleanValue()
public boolean booleanValue()
Returns the value of this Boolean object as a boolean primitive.
以布尔基元的形式返回此Boolean对象的值。
So if our bool object is: 所以如果我们的bool对象是:
Boolean bool = new Boolean(true);
This is equivalent: 这相当于:
bool.booleanValue() == true;
The ternary comparator here is redundant and decrease the readability. 这里的三元比较器是冗余的,降低了可读性。
For sure in your code you have one atomic operation less. 在您的代码中,您可以减少一个原子操作。 See this for good explanation: https://stackoverflow.com/a/493258/1509129
有关详细说明,请参阅此处: https : //stackoverflow.com/a/493258/1509129
I don't think there's a final answer to why it's written that way, since as Felipe Fernández points out there's no functional reason to do it 我不认为这是为什么这样写的最终答案,因为正如费利佩·费尔南德斯指出的那样,没有任何功能上的理由
However, my guess would be that it's done to make the method symmetric with others in the same class returning Boolean
objects, such as toBooleanObject
但是,我的猜测是,要使方法与同一个类中的其他人对称,返回
Boolean
对象,例如toBooleanObject
public static Boolean toBooleanObject(boolean bool) {
return bool ? Boolean.TRUE : Boolean.FALSE;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.