Is It Bad to Explicitly Compare Against Boolean Constants E.G. If (B == False) in Java

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

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.

if (boolean == false) vs. if (!boolean)

Apart from "readability", no. They're functionally equivalent.

("Readability" is in quotes because I hate == false and find ! much more readable. But others don't.)

if (boolean == false) vs. if (!boolean)

Apart from "readability", no. They're functionally equivalent.

("Readability" is in quotes because I hate == false and find ! much more readable. But others don't.)

Explicitly evaluate both conditions when using Boolean AND

You'd just execute the conditions first, before testing with and:

# explicitly execute the conditions first, compare the outcomes later
test1, test2 = x == 2, myList.pop() == 3
if test1 and test2:

For your case that can be simplified down to just the myList.pop() call:

# explicitly pop a value from myList, regardless of what x == 2 returns
myList_value = myList.pop()
if x == 2 and myList_value == 3:

Of course, you could also just have swapped the tests:

if myList.pop() == 3 and x == 2:

to ensure that the list.pop() method is always executed.

Otherwise, the & bitwise operator is overloaded for Python booleans just like it is in Java:

>>> from itertools import product
>>> for a, b in product([False, True], repeat=2):
... print('{a!r:5} and {b!r:5}: {o1!r:5} {a!r:5} & {b!r:5}: {o2!r:5}'.format(a=a, b=b, o1=a and b, o2=a & b))
...
False and False: False False & False: False
False and True : False False & True : False
True and False: False True & False: False
True and True : True True & True : True

And as such you can use it to avoid short-circuiting, but only if both operands are booleans:

>>> def foo():
... print 'called!'
... return False
...
>>> def bar():
... print 'also called!'
... return False
...
>>> foo() and bar()
called!
False
>>> foo() & bar()
called!
also called!
False

However, I'd consider making use of this unpythonic, and indicative of bad coding style. Restructure your code to not have to rely on this in the first place.

How to compare Boolean?

From your comments, it seems like you're looking for "best practices" for the use of the Boolean wrapper class. But there really aren't any best practices, because it's a bad idea to use this class to begin with. The only reason to use the object wrapper is in cases where you absolutely must (such as when using Generics, i.e., storing a boolean in a HashMap<String, Boolean> or the like). Using the object wrapper has no upsides and a lot of downsides, most notably that it opens you up to NullPointerExceptions.

Does it matter if '!' is used instead of .equals() for Boolean?

Both techniques will be susceptible to a NullPointerException, so it doesn't matter in that regard. In the first scenario, the Boolean will be unboxed into its respective boolean value and compared as normal. In the second scenario, you are invoking a method from the Boolean class, which is the following:

public boolean equals(Object obj) {
if (obj instanceof Boolean) {
return value == ((Boolean)obj).booleanValue();
}
return false;
}

Either way, the results are the same.

Would it matter if .equals(false) was used to check for the value of the Boolean checker?

Per above, no.

Secondary question: Should Boolean be dealt differently than boolean?

If you absolutely must use the Boolean class, always check for null before performing any comparisons. e.g.,

Map<String, Boolean> map = new HashMap<String, Boolean>();
//...stuff to populate the Map
Boolean value = map.get("someKey");
if(value != null && value) {
//do stuff
}

This will work because Java short-circuits conditional evaluations. You can also use the ternary operator.

boolean easyToUseValue = value != null ? value : false;

But seriously... just use the primitive type, unless you're forced not to.

What is the preferred way to write boolean expressions in Java

I prefer the first style because it is more natural for me to read. It's very unusual to see the second style.

One reason why some people might prefer the second over another alternative:

if (isValid == false) { ... }

is that with the latter you accidentally write a single = instead of == then you are assigning to isValid instead of testing it but with the constant first you will get a compile error.

But with your first suggestion this issue isn't even a problem, so this is another reason to prefer the first.

Best Practice: if(foo== false) or if(!foo)

Number 2, along with "foo" having a descriptive name, so that the code reads well:

if (!hasPurple)
...

What is better java syntax: if (isSomething() == false) { or if (!isSomething()) {

The hidden third option is to name your variables and methods properly.

Instead of

if (!isDisabled()) {
...
}

use

if (isEnabled()) {
...
}

or if you want to check for the negative:

boolean disabled = !isEnabled();
if (disabled) {
...
}

or add both methods:

boolean isDisabled() {
return !isEnabled();
}

Edit: I found this question: Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?

Use of Boolean? in if expression

You can compare nullable boolean with true, false or null using equality operator:

var b: Boolean? = null
if (b == true) {
// b was not null and equal true
}
if (b == false) {
// b is false
}
if (b != true) {
// b is null or false
}


Related Topics



Leave a reply



Submit