The Anti-Pattern: if (opt.isPresent()) opt.get()
What you'll learn: You'll recognize the most common Optional misuse—combining isPresent() with get()—and understand why it completely defeats Optional's purpose.
The Problem with This Pattern
When developers first encounter Optional, they often write code like this:
Optional<String> result = findUsername(userId);
if (result.isPresent()) {
String username = result.get();
System.out.println("Username: " + username);
}
This looks familiar—it mirrors traditional null-checking:
String result = findUsername(userId);
if (result != null) {
System.out.println("Username: " + result);
}
Here's the problem: These two approaches are functionally identical. The Optional version adds zero safety or expressiveness. You've simply replaced != null with isPresent() and added an extra unwrapping step with get().
Why This Defeats Optional's Purpose
Optional exists to force deliberate handling of absence through its API. When you use isPresent() followed by get(), you're back to manual checking—the exact pattern Optional was designed to eliminate.
Think of it like this: You bought a safe with a sophisticated combination lock (Optional's declarative methods), but instead you're just checking if the door is closed before yanking it open. You're not using the lock's actual security features.
This anti-pattern adds overhead (creating an Optional object) without any benefit. You're still doing imperative, manual checking instead of using Optional's declarative methods that handle presence and absence elegantly.
Key Takeaway: The pattern if (opt.isPresent()) opt.get() is a code smell that indicates you're not truly using Optional—you're just wrapping null checks in extra ceremony. Optional should change how you handle absence, not just what you call the methods.