New rule suggestion: "Boolean" objects should be used in a null safe way inside of expressions

java

(Andreas Schnapp) #1

If a Boolean object is used inside of an expression and it’s value is null then a NullPointerException will occur. (auto unboxing of a null Boolean value)

This causes bugs which are really difficult to see in merge request reviews (because mostly you think of a boolean value which can’t be null) and such error can have a huge impact .

I suggest that there should be a extra rule for it.

So a Boolean should not be checked like this:

Boolean flag = service.getFlag();
// that's the unsafe call which could cause a null pointer exception
if(flag) {
    // do something
}

Instead it should be handled like that (or with a null check beforehand):

Boolean flag = service.getFlag();
// that's a null safe call
if(Boolean.TRUE.equals(flag)) {
    // do something
}

Here is a nice description about this kind of issue:

Please let me know what you are thinking about creating this rule.


(Alexandre Gigleux) #3

Hello Andreas,

That’s a really interesting case.

Instead of introducing a new rule, what about using S2447: Null should not be returned from a “Boolean” method that prevents a method returning a Boolean object to return a null value?

Alex


(Andreas Schnapp) #4

Hello @Alexandre_Gigleux,

thanks for the suggestion.

But I have already seen this Rule, I guess there are much cases where you could avoid this kind of issue with this rule but there are also cases where this rule is not a good fit.

F.e. I have a generated Webservice Client (from a wsdl) which could give back null for several Boolean fields (getter methods), if the information is not available. And the return of Boolean inside the getter make sense and are OK (at least in my opinion)

But then there are several validations mapping etc… done based on the data.
And everytime when a Boolean is directly used inside an expression there is the danger of getting a NPE.