Anti-Pattern: Returning null Instead of Optional.empty()
You'll learn why returning null from methods that declare Optional as their return type completely undermines Optional's purpose.
The Broken Contract
When you declare a method's return type as Optional<T>, you're making a promise: "I will return an Optional that either contains a value or is explicitly empty." The caller expects to receive an Optional object they can safely work with using methods like isPresent(), map(), or orElse().
If you return null instead of Optional.empty(), you've violated that contract. The caller must now check for null before they can safely use any Optional methods—exactly the problem Optional was designed to solve!
The Analogy
Imagine ordering a "mystery box" from a store. The box might contain a prize or be empty, but you always get a box. Now imagine the store sometimes ships nothing at all—not even an empty box. You'd have to check your doorstep for the presence of a box before you could even open it. That's what returning null from an Optional-returning method does.
Why This Happens
Developers sometimes do this out of habit from pre-Optional code, or by mistakenly thinking "null means absence" even when using Optional. But Optional already has a perfectly good way to represent absence: Optional.empty().
The Correct Pattern
// WRONG - defeats the entire purpose
public Optional<String> findUserName(int id) {
if (id < 0) {
return null; // Caller must null-check the Optional!
}
return Optional.of("Alice");
}
// RIGHT - maintains the contract
public Optional<String> findUserName(int id) {
if (id < 0) {
return Optional.empty(); // Safe, expected behavior
}
return Optional.of("Alice");
}
Key Takeaway: If your method returns Optional<T>, always return an Optional instance—either containing a value or Optional.empty(). Returning null destroys the null-safety guarantee and forces callers back into defensive null-checking.