[Java] check Boolean passed to method with boolean argument

I just stumbled on that hard-to-find issue, that a Boolean was passed to a setter which accepts boolean:

a.setBusy( b.isBusy() )

The result was a NullPointerException. I immediately checked, why b could be null, but it never was.
The reason was that b.isBusy() returned null.
I found this to be quite troublesome, I found the reason just because I asked a friend, who already had that Problem.

It’s a hard to find Problem, so I was surprised to find no rule to check for that.

This is another Topic than [Java] check Boolean assignment to boolean , because I did not assign a Boolean to a boolean, but handed it over as an argument.

Noncompliant Code

void setBusy( boolean isBusy ) {
  // ...
}

Boolean isBusy() {
  // may return null
}

[...]

setBusy( isBusy() )  // could throw NullPointerException

Compilant Code

void setBusy( boolean isBusy ) {
  // ...
}

Boolean isBusy() {
  // may return null
}

[...]

setBusy( Boolean.TRUE.equals( isBusy() ) )

type
Bug, Vulnerability

Hello @Heinerion, welcome to the SonarSource community.

Thank you for taking the time to write a clear description of the problem, with relevant related information, it’s always appreciated.

I agree that this is a tricky problem and would be glad to be able to rely on static analysis to detect it.
The post you linked is indeed not the same problem, but the ticket stated there (SONARJAVA-2126) fits well the problem you described: we are indeed in the situation where a potentially null boxed primitive is unboxed. I added an example similar to what you described to make sure we don’t forget this case.

Also, note that S5411 is raising a code smell when using boxed Boolean in a boolean expression. We could support the case you described in this rule, but I don’t think it’s worth it since we are currently not fully satisfied with the current results, and might end up rethinking it.

Best,
Quentin

Hello @Quentin,

thanks for your fast reply.
I consider SONARJAVA-2126 to resolve my Problem, so I mark your answer as Solution.

Thanks,
Heiner

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.