Boolean.FALSE: When should it be used?

99 Views Asked by At

I have been reading the book Crafting Interpreters by Robert Nystrom and came across the following code:

if (!scopes.isEmpty() && scopes.peek().get(expr.name.lexeme) == Boolean.FALSE) { // <- Focus here
      // some code here      
}

In other places where we declare variables, the book uses the more usual syntax boolean a = false notation. Stack Overflow has many answers explaining what is Boolean.FALSE but there is none stating when it should be used.

Is it a common/good practice to write Boolean.FALSE (or Boolean.TRUE) in the context of equality operators? If yes, then why?

Or, is it a matter of personal preference and code readability?

2

There are 2 best solutions below

4
k314159 On BEST ANSWER

Is it a common/good practice to write Boolean.FALSE (or Boolean.TRUE) in the context of equality operators? If yes, then why?

It is not common/good practice to use Boolean.FALSE in general, but there are specific situations in which Boolean.FALSE can be useful. One such situation is the code in your question.

Basically, that code means the same thing as if (!scopes.isEmpty() && scopes.peek().get(expr.name.lexeme) != null && !scopes.peek().get(expr.name.lexeme)) but without calling peek().get(...) twice.

If you wanted the exact same results, but without using Boolean.FALSE, you would have to write it like this:

Boolean tmp;
if (!scopes.isEmpty() && (tmp = scopes.peek().get(expr.name.lexeme)) != null && !tmp) {
   ...
}

So, using xxx == Boolean.FALSE can have its uses in certain specific situations.

1
Nathan Hughes On

Boolean wrapper values TRUE and FALSE are cached, so even though == compares references, those references are always the same and == works as if value-based.

There is nothing wrong here. It seems likely the value being matched is a Boolean wrapper type and the author is trying to avoid unneeded unboxing, comparing references is going to be much faster.

Also unboxing risks an NPE if the variable getting unboxed is null, the == check avoids this possibility (thanks k314159).