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

Anti-Pattern: Optional.of() with Nullable Values

Why using of() instead of ofNullable() for potentially null values causes immediate NPEs.

Anti-Pattern: Optional.of() with Nullable Values

You'll learn why using Optional.of() with potentially null values defeats Optional's safety purpose and causes immediate crashes.

The Risky Assumption

When you call Optional.of(value), you're making a strong guarantee: "this value is definitely not null." Java trusts you and wraps the value without checking. But if that value is null, you get an immediate NullPointerException—the very thing Optional was designed to prevent!

This is like putting a "Fragile" sticker on an already-broken package. You've promised something safe, but delivered danger.

Why It's an Anti-Pattern

String getUserEmail(String userId) {
    String email = database.findEmail(userId); // might return null!
    return Optional.of(email); // BOOM! NPE if email is null
}

The problem: database.findEmail() might return null, but Optional.of() requires a non-null value. The NPE happens immediately at the Optional creation, not later when accessing the value. You've gained nothing from using Optional.

The Correct Approach

String getUserEmail(String userId) {
    String email = database.findEmail(userId);
    return Optional.ofNullable(email); // Safe! Handles null gracefully
}

Use Optional.ofNullable() when you're unsure whether the value is null. It creates Optional.empty() for null values and wraps non-null values safely.

When of() Is Appropriate

Only use of() when you have absolute certainty the value cannot be null:

Optional<String> definitelyPresent = Optional.of("hardcoded"); // Safe
Optional<Integer> afterCheck = Optional.of(list.size()); // Safe, size() never null

Key Takeaway: Using Optional.of() with nullable values causes immediate NPEs, defeating Optional's purpose entirely. Always use Optional.ofNullable() unless you can guarantee non-null values.