Search code examples
javanulljava-11null-check

Efficient null check in Java 11


I need to use a getter which is 3 levels down in the object.

response.getServiceError().getErrorCode()

It is possible one or more objects could be NULL. Now, I am doing this

if (response != null && response.getServiceError() != null && response.getServiceError().getErrorCode() != null && response.getServiceError().getErrorCode().equals("errCode123")) {
     //doSomething;
}

Is there a better and/or elegant way to construct that if condition?


Solution

  • Use Optional!

    Optional.ofNullable(response)
        .map(Response::getServiceError)
        .map(ServiceError::getErrorCode)
        .filter(code -> code.equals("errCode123"))
        .ifPresent(code -> {
            // doSomething
        });