0

Here are two code samples where the second uses an Optional:

1:

String email = userService.getEmailAddress();

if(email != null) {
    emailService.send();
}

2:

Optional<String> email = userService.getEmailAddress();

if(email.isPresent()) {
   emailService.send();
}

The code is almost identical even though I am using Optional in the second sample. What is the benefit of using isPresent() with Optional objects vs != null? I understand Optional was introduced to help deal with NullPointerExceptions and to make code less verbose but I'm not seeing the benefit in terms of the amount of code that needs to be written. Is there a less verbose/cleaner way of writing the code in the example given?

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
kill-9
  • 102
  • 2
  • `userService.getEmailAddress().ifPresent(email -> emailService.send());` – khelwood May 20 '22 at 10:01
  • 1
    `Optional` _forces_ you to check presence/absence of the value. Checking for null can easily be forgotten and your program will then crash at run time. The `Optional` type clearly expresses the intent that there might not be a (non-empty) result. – knittl May 20 '22 at 10:01

0 Answers0