javasonarlint-intellij

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


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?


Solution

  • 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.