5
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?

DKWoo
  • 327
  • 5
  • 17

2 Answers2

6

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.

dan1st
  • 12,568
  • 8
  • 34
  • 67
0

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.

nomad
  • 847
  • 7
  • 10