how to handle Sonarlint java:S2259 (Null pointers should not be dereferenced)

6.2k Views Asked by At
if (res.getBody() == null || res.getBody().getServiceResult() == null) {
  return; //
}

in above code, sonarlint complains that SonarLint: A "NullPointerException" could be thrown; "getBody()" can return null. (from res.getBody().getServiceResult() )

I think "res.getBody() == null" checks null first so it should go to return line, not reach to next if condition.

Am I thinking something wrong?

2

There are 2 best solutions below

0
On BEST ANSWER

res.getBody() == null || res.getBody().getServiceResult() == null)

Sonar detects that res.getBody() can be null when you do the check res.getBody()==null.

After that, you call res.getBody() again.

It could be non-null the first time but not the second time, sonar does not know this.

In order to fix this, just do the following:

BodyType body=res.getBody();
if (body == null || body.getServiceResult() == null) {
  return;
}

You can then even reuse body after that.

If you are absolutely sure that res.getBody() stays null and is also not modified by another thread, you could also use a //NOSONAR comment in order to suppress the warning.

0
On

It seems res also can be null.

Try

if (res == null || res.getBody() == null || res.getBody().getServiceResult() == null) {
  return; //
}

Such long getter chains can also be replaced with Optional + map + ifPresent lambda style.