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?
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
.
Java boolean operators are denoted by |, ||, &, &&, <, >, <=, >=, ^, != , ==. These logical boolean operators help in specifying the condition that will have the two return values – “true” or “false”.
The . equals() methods seems to be roughly 4 times slower than == . Thus, it is safe to say that . equals() hinders performance and that == is better to use in most cases to compare Boolean .
Notice that the boolean in the if-test (true or false) happens to be the same as the value we want to return. If the test value is true, we return true. If the test value is false, we return false.
== is an operator that returns true if the contents being compared refer to the same memory or false if they don't. If two strings compared with == refer to the same string memory, the return value is true; if not, it is false. The return value of == above is false, as "MYTEXT" and "YOURTEXT" refer to different memory.
It's not necessarily bad, it's just superfluous. Also, the actual variable name weights a lot. I would prefer for example if (userIsAllowedToLogin)
over if (b)
or even worse if (flag)
.
As to the performance concern, the compiler optimizes it away at any way.
As to the authoritative sources, I can't find something explicitly in the Java Code Conventions as originally written by Sun, but at least Checkstyle has a SimplifyBooleanExpression
module which would warn about that.
You should not use the first style. I have seen people use:
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 )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With