Search code examples
javasonarqube

sonar rule "possible null pointer exception"


I'm finding a problem in my Sonar I don't know how to solve.

The error I have is:

Possible null pointer dereference in mypackage.myMethod(String) due to return value of called method

At the very begining it was:

 response.getBody().getData();

So what I did was:

return (response != null && response.getBody() != null) ? response.getBody().getData() : null;

But the error is still there.

Am I missunderstanding the error?? How can I solve?


Solution

  • Each time you invoke a method, you might get back a different result. You may know that you will get the same result back each time, but Sonarqube doesn't.

    Assign response.getBody() to a variable so you don't have to call it again:

    if (response != null) {
      var body = response.getBody();
      if (body != null) {
        return body.getData();
      }
    }
    return null;
    

    You can do it with Optional, alternatively:

    return Optional.ofNullable(response).map(ResponseType::getBody).map(BodyType::getData).orElse(null);