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:
- It's procedural, not declarative - You're telling the code how to check, not what to do with presence or absence
- It's verbose - More code to write and read than either null checks or functional alternatives
- 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.