Use Optional.ofNullable instead of if else

Publié le 27 septembre 2023 à 10:18

Introduction:

Use Optional.ofNullable instead of if else

Introduction

This article represents some code snippets examples in java 8+ using for some Spring boot 2.+
First of all i will present a code snippet, and a second one as another way to write the first one.

Replace if else Bloc with Optional.ofNullable

In Java, the code readability and robustness are one of the important factors that can affect the maintainability
and quality of your application.
One way to enhance both aspects is by using Java’s Optional class.
Using Optional make it easier to read the code especially if we are facing a lot of conditions.
Look at this method :

  private String createDetail(BookException exception) {
    if (exception.getBody() == null) {
      if (exception.getCause() != null) {
        var message = exception.getCause().getMessage();
        if (message != null) {
          return message;
        }
      } else {
        return exception.getMessage();
      }
    }
    return exception.getBody();
  }

This Method is from an Exception Handler which tries to get a Detail from a Book type Exception.
We can simplify this code by using Optional.ofNullable.
All the values that are compared to null should be wrapped in an Optional.ofNullable.

  private String createDetail(BookException exception) {
    return Optional.ofNullable(exception.getBody())
             .orElseGet(() -> Optional.ofNullable(exception.getCause())
               .map(cause -> Optional.ofNullable(cause.getMessage()))
                 .orElse(exception.getMessage()))
               .orElse(infrastructureException.getMessage()));
    }

Now note the difference here, The Optional.ofNullable replaces the
if (exception.getBody() == null)

Ajouter un commentaire

Commentaires

Il n'y a pas encore de commentaire.