在 Java 中显式地与布尔常量(例如 if (b == false) 进行比较)是不是很糟糕?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2661110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:28:54  来源:igfitidea点击:

Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?

javacoding-styleboolean

提问by polygenelubricants

Is it bad to write:

是不是不好写:

if (b == false) //...

while (b != true) //...

Is it alwaysbetter to instead write:

改写是否总是更好:

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?

大概在性能上没有区别(或者有没有?),但是你如何权衡两者之间的明确性、简洁性、清晰性、可读性等?

Update

更新

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.

为了限制主观性,我也很欣赏权威编码风格指南中的任何引用,关于哪种总是更可取或何时使用。



Note: the variable name bis just used as an example, ala fooand bar.

注意:变量名b仅作为示例,alafoobar.

采纳答案by BalusC

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).

这不一定是坏事,它只是多余的。此外,实际的变量名称权重很大。我更喜欢if (userIsAllowedToLogin)上面的例子,if (b)甚至更糟if (flag)

As to the performance concern, the compiler optimizes it away at any way.

至于性能问题,编译器会以任何方式对其进行优化。

Update: as to the authoritative sources, I can't find something explicitly in the Sun Coding Conventions, but at least Checkstylehas a SimplifyBooleanExpressionmodule which would warn about that.

更新:至于权威来源,我在Sun Coding Conventions 中找不到明确的内容,但至少Checkstyle有一个SimplifyBooleanExpression模块会对此发出警告。

回答by Michael Mrozek

I've never seen the former except in code written by beginners; it's always the latter, and I don't think anyone is really confused by it. On the other hand, I think

除了初学者编写的代码,我从未见过前者;总是后者,我认为没有人真的对此感到困惑。另一方面,我认为

int x;
...
if(x) //...

vs

对比

if(x != 0) //...

is much more debatable, and in that case I do prefer the second

更有争议,在这种情况下,我更喜欢第二个

回答by ChaosPandion

In my opinion it is simply annoying. Not something I would cause a ruckus over though.

在我看来,这简直令人讨厌。不过,我不会引起骚动。

回答by Head Geek

I prefer the first, because it's clearer. The machine can read either equally well, but I try to write code for other peopleto read, not just the machine.

我更喜欢第一个,因为它更清晰。机器可以同样好地阅读,但我尝试编写代码供其他阅读,而不仅仅是机器。

回答by Thomas

You should not use the first style. I have seen people use:

您不应该使用第一种样式。我见过人们使用:

  • if ( b == true )
  • if ( b == false )
  • if ( b == true )
  • if ( b == false )

I personally find it hard to read but it is passable. However, a big problem I have with that style is that it leads to the incredibly counter-intuitive examples you showed:

我个人觉得很难读,但还可以。然而,我对这种风格的一个大问题是它导致了你展示的令人难以置信的反直觉的例子:

  • if ( b != true )
  • if ( b != false )
  • if ( b != true )
  • if ( b != false )

That takes more effort on the part of the reader to determine the authors intent. Personally, I find including an explicit comparison to true or false to be redundant and thus harder to read, but that's me.

这需要读者付出更多努力来确定作者的意图。就我个人而言,我发现包含对真或假的明确比较是多余的,因此更难阅读,但这就是我。

回答by Alan Moore

The overriding reason why you shouldn't use the first style is because both of these are valid:

不应该使用第一种样式的首要原因是因为这两种样式都是有效的:

if (b = false) //...

while (b = true) //...

That is, if you accidentally leave out one character, you create an assignment instead of a comparison. An assignment expression evaluates to the value that was assigned, so the first statement above assigns the value falseto band evaluates to false. The second assigns trueto b, so it always evaluates to true, no matter what you do with binside the loop.

也就是说,如果您不小心遗漏了一个字符,您将创建一个赋值而不是一个比较。赋值表达式的计算结果为已分配的值,因此上面的第一个语句将值分配falseb并计算为false。第二个赋值trueb,所以它总是计算为true,无论你b在循环内做什么。

回答by Mahesh Velaga

IMHO, I think if you just make the bool variable names prepended with "Is", it will be self evident and more meaningful and then, you can remove the explicit comparison with trueor false

恕我直言,我认为如果你只是让 bool 变量名加上"Is",它会不言自明且更有意义,然后,你可以删除与trueor的显式比较false

Example:

例子:

isEdited  // use IsEdited in case of property names
isAuthorized // use IsAuthorized in case of property names

etc

等等

回答by Thorbj?rn Ravn Andersen

This is strongly a matter of taste.

这是一个强烈的品味问题。

Personally I've found that if (!a) {is a lot less readable(EDIT: to me) than if (a == false) {and hence more error prone when maintaining the code later, and I've converted to use the latter form.

就我个人而言,我发现它的可读性if (!a) {要低得多(编辑:对我来说),因此在以后维护代码时更容易出错,我已经转换为使用后一种形式。if (a == false) {

Basically I dislike the choice of symbols for logic operations instead of words (C versus Pascal), because to mea = 10 and not b = 20reads easier than a == 10 && !(b==20), but that is the way it is in Java.

基本上我不喜欢为逻辑运算选择符号而不是单词(C 与 Pascal),因为对我来说a = 10 and not b = 20读起来比 更容易a == 10 && !(b==20),但这就是它在 Java 中的方式。

Anybody who puts the "== false" approach down in favour of "!" clearly never had stared at code for too long and missed that exclamation mark. Yes you can get code-blind.

任何放弃“== false”方法而支持“!”的人 显然,他从来没有盯着代码看太久,也没有错过那个感叹号。是的,您可以无码。

回答by Peter Lawrey

Personally, I would refactor the code so I am not using a negative test. for example.

就个人而言,我会重构代码,这样我就不会使用负面测试。例如。

if (b == false) {
   // false
} else {
   // true
}

or

或者

boolean b = false;
while(b == false) {
  if (condition)
      b = true;
}

IMHO, In 90% of cases, code can be refactored so the negative test is not required.

恕我直言,在 90% 的情况下,代码可以重构,因此不需要负面测试。

回答by fastcodejava

I would say it is bad.

我会说这很糟糕。

while (!b) {
    // do something 
}

reads much better than

读起来比

while (b != true) {
    // do something 
}