0
votes

I am fetching some data from a remote service using Spring's RestTemplate:

ResponseEntity<....> result = restTemplate.exchange(....);

...and then I am using result for further processing, and hence I am invoking various methods on it, like:

result.getHeaders().getContentType().getType()
result.getBody()
result.getHeaders().getContentType().getSubtype()

Sonar doesn't like this code and reports 'Possible null pointer dereference' error on almost all of these method calls. It seems I need to have null check on almost every return value.

This makes my code with too many null checks.

Can this be avoided?

1
Yes, turn off the check - Michael
That's not in my hand. Its team level setting. - Mandroid
Then make sure you prematurely avoid NPEs. - Giorgi Tsiklauri

1 Answers

0
votes

Use Optional from java 8 JavaDocs:

String contentType = Optional.ofNullable(result)
  .map(HttpResponse::getHeaders)
  .map(Headers::getContentType)
  .map(ContentType::getType)
  .orElse(null);

HttpResponse should be the type of result, Headers should be the return type of getHeaders() and so on.

You can use other terminating operators other than orElse():

.orElseGet(() -> someOtherProcess());
.orElseThrow(() -> new RuntimeException("Content Type was Null"));