显式比较布尔常数是不好的if(b == false)in Java? [英] Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?
问题描述
写不好:
if (b == false) //...
while (b != true) //...
最好改为写:
Is it always better to instead write:
if (!b) //...
while (!b) //...
大概没有性能差异
为了限制主观性,我还将感谢权威编码风格指南中的任何引用,这些引用总是优选的或在何时使用。
To limit the subjectivity, I'd also appreciate any quotes from authoritative coding style guidelines over which is always preferable or which to use when.
注意:变量名称 b
只是作为一个例子,ala foo
和 bar
。
Note: the variable name b
is just used as an example, ala foo
and bar
.
推荐答案
这不一定是坏的,它只是多余。此外,实际变量名称权重很多。我更喜欢例如 if(userIsAllowedToLogin)
以上 if(b)
或更糟糕 if (flag)
。
It's not necessarily bad, it's just superfluous. Also, the actual variable name weights a lot. I would prefer for example if (userIsAllowedToLogin)
above if (b)
or even worse if (flag)
.
至于性能问题,编译器以任何方式优化它。
As to the performance concern, the compiler optimizes it away at any way.
更新:对于权威来源,我无法在 Sun Coding约定,但至少 Checkstyle 有 SimplifyBooleanExpression
模块,会发出警告。
Update: as to the authoritative sources, I can't find something explicitly in the Sun Coding Conventions, but at least Checkstyle has a SimplifyBooleanExpression
module which would warn about that.
这篇关于显式比较布尔常数是不好的if(b == false)in Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!