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
.
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.
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.
It's not necessarily bad, it's just superfluous. Also, the actual variable name weights a lot. I would prefer for example
if (userIsAllowedToLogin)
aboveif (b)
or even worseif (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.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
vs
is much more debatable, and in that case I do prefer the second
Personally, I would refactor the code so I am not using a negative test. for example.
or
IMHO, In 90% of cases, code can be refactored so the negative test is not required.
I would say it is bad.
reads much better than