Is there any reason for expression like !Boolean.FALSE.equals()?

Viewed 70

When browsing the Spring's source code, I encountered code like if (!Boolean.FALSE.equals(pv.conversionNecessary)) {...}

After some research, I also found codes like !Boolean.FALSE.equals and !Boolean.TRUE.equals exist in other open-source projects too.

I wonder what's the possible reasons for not using the apparently concise expression?

1 Answers

There are various reasons why this kind of thing might be necessary.

In this example, pv is an instance of PropertyValue which declares the conversionNecessary as follows:

/** Package-visible field that indicates whether conversion is necessary. */
@Nullable
volatile Boolean conversionNecessary;

(source code)

From this, we can infer that it is not unexpected for conversionNecessary to be null.

So ... the verbose form if (!Boolean.FALSE.equals(pv.conversionNecessary)) {...} is dealing with the null case. Boolean.FALSE.equals(null) is false.

By contrast, the more concise form if (!pv.conversionNecessary) {...} would throw an NPE.

It is also worth noting that since conversionNecessary is volatile here, an alternative version that did an explicit null check would need to use a temporary variable to avoid race conditions; e.g.

Boolean necessary = pv.conversionNecessary;
if (necessary == null || necessary) { ... }

Another scenario where you might do this kind of thing is if the declared type of the variable is Object rather than Boolean.

Related