Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?(明确比较布尔常量是否很糟糕,例如如果(b == false)在Java中?)
问题描述
写不好:
if (b == false) //...
while (b != true) //...
总是改写更好:
if (!b) //...
while (!b) //...
大概在性能上没有区别(或者有吗?),但是你如何权衡两者之间的明确性、简洁性、清晰性、可读性等?
Presumably there is no difference in performance (or is there?), but how do you weigh the explicitness, the conciseness, the clarity, the readability, etc between the two?
为了限制主观性,我还希望引用权威编码风格指南中的任何引用,这些引用总是更可取或何时使用.
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
只是作为例子,还有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 编码约定,但至少 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.
这篇关于明确比较布尔常量是否很糟糕,例如如果(b == false)在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:明确比较布尔常量是否很糟糕,例如如果(b == false)在Java中?
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01