Course contentsShow
← Java
Lesson 1819 of 2,87037. Optional for Null SafetyFree lesson

Anti-Pattern: isPresent() Before get()

How isPresent() checks followed by get() recreate null checks and miss functional alternatives.

Anti-Pattern: isPresent() Before get()

You'll learn why the common pattern of checking isPresent() before calling get() defeats the entire purpose of using Optional in the first place.

The Problem: Reinventing Null Checks

When you write:

Optional<String> userEmail = findUserEmail(userId);

if (userEmail.isPresent()) {
    String email = userEmail.get();
    sendEmail(email);
}

You've essentially recreated the exact null-checking pattern Optional was designed to replace:

String userEmail = findUserEmail(userId);

if (userEmail != null) {
    sendEmail(userEmail);
}

The Optional version is actually more verbose and provides no additional benefit. You've wrapped a value in a container just to immediately unwrap it with imperative checking logic.

Why This Is an Anti-Pattern

This approach misses the functional alternatives that make Optional valuable:

  1. It's procedural, not declarative - You're telling the code how to check, not what to do with presence or absence
  2. It's verbose - More code to write and read than either null checks or functional alternatives
  3. It doesn't compose - You can't chain further operations cleanly

The Functional Alternative

Instead of isPresent() + get(), use the functional methods you've already learned:

Optional<String> userEmail = findUserEmail(userId);

userEmail.ifPresent(email -> sendEmail(email));
// Or simply:
userEmail.ifPresent(this::sendEmail);

This is concise, expressive, and impossible to get wrong. The action only happens if the value is present—no manual checking required.

Key Takeaway: If you find yourself writing isPresent() followed by get(), stop and reach for ifPresent(), map(), orElse(), or another functional method instead. The isPresent()/get() combination is a code smell that signals you're using Optional as a fancy null wrapper rather than embracing its functional design.