Is it bad to explicitly compare against boolean co

2019-01-03 02:45发布

Is it bad to write:

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

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

Is it always better 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 b is just used as an example, ala foo and bar.

14条回答
ら.Afraid
2楼-- · 2019-01-03 03:13

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

查看更多
放我归山
3楼-- · 2019-01-03 03:16

One of the reasons the first one (b==false) is frowned upon is that beginners often do not realize that the second alternative (!b) is possible at all. So using the first form may point at a misconception with boolean expressions and boolean variables. This way, using the second form has become some kind of a sjiboleth: when someone writes this, he/she probably understands what's going on.

I believe that this has caused the difference to be considered more important than it really is.

查看更多
混吃等死
4楼-- · 2019-01-03 03:18

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.

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.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-03 03:24

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

查看更多
我想做一个坏孩纸
6楼-- · 2019-01-03 03:25

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.

查看更多
smile是对你的礼貌
7楼-- · 2019-01-03 03:28

I would say it is bad.

while (!b) {
    // do something 
}

reads much better than

while (b != true) {
    // do something 
}
查看更多
登录 后发表回答