Home Bad boolean zen
Do not compare to 'true'
Never directly compare a value against true
– doing so is redundant.
That is, never do someExpression == true
. Instead, do someExpression
instead, which is exactly equivalent.
After all, since someExpression
is a boolean,
comparing it to a boolean will just produce yet another boolean, which is redundant.
We call this kind of comparison bad boolean zen.
Consider the following code:
if (number < 0 == true) { System.out.println("The number is negative."); }
While at first glance, this code snippet seems reasonable, it actually contains some
unnecessary code. Specifically, notice that the == true
part is unnecessary.
If we remove it, the if statement will do the exact same thing:
if (number < 0) { System.out.println("The number is negative."); }
Therefore, since we can remove it, we should. After all, if we're comparing some value
to true
, that means that the value must already be a boolean to begin with.
In that case, just use the value directly. Don't beat around the bush.
A good rule of thumb is that you should never type the characters
== true
in Java. Whenever you see that code snippet, it can almost always
be deleted with zero impact on the code.
Use the "!" negation operator instead of comparing to false
As an extension of the previous rule, you should never do value == false
or value != true
– this would also count as bad boolean zen. Instead, do
!value
instead.
The reason why you should always prefer using the negation !
operator is
because it's more concise and reads better.
It also makes it unambiguously clear that we're flipping the boolean sign of the value.
Be careful when returning or setting a boolean
When writing a method that returns a boolean be very careful to make sure that your
code has good boolean zen. If you need an if statement to decide if something should be
true
or false
, you can often simplify away the entire if
statement.
We see this often with boolean methods:
public boolean isNegative(int number) { if (number < 0) { return true; } else { return false; } }
Since the condition must already be either true
or false
,
we can simplify the code to the following:
public boolean isNegative(int number) { return number < 0; }
(Note that this method is also a trivial method and probably shouldn't exist in the first place).
Similarly, you should be careful when setting a boolean value. Don't do this:
boolean isNegative; if (number < 0) { isNegative = true; } else { isNegative = false; }
Instead, do this:
boolean isNegative = number < 0;