Sub topic 13
Using Optional Well: Guidelines and Anti-Patterns
You now know the main Optional methods. This chapter covers where Optional belongs and where it does not. An anti-pattern is a common habit that looks reasonable but causes problems. Avoiding a few of them keeps your code clean and safe.
The Main Rule: Use Optional as a Return Type
Optional was added to Java for one main job: to be the return type of a method that might have no result. The return type is the kind of value a method gives back. When a caller sees Optional<String>, they know right away that the answer may be missing, and they have to deal with that case.
Java's designers did not mean for Optional to replace every null in your program. Using it in other places adds clutter and slows code down a little, and it gives you nothing in return.
Guidelines at a Glance
| Do | Don't |
|---|---|
| Return `Optional<T>` when a result may be missing | Use `Optional` as a field in a class |
| Return an empty list instead of `Optional<List<T>>` | Take `Optional` as a method parameter |
| Use `orElse`, `orElseGet`, or `orElseThrow` | Call `get()` without knowing a value exists |
| Return `Optional.empty()` for "no result" | Return `null` from a method whose return type is `Optional` |
| Use `OptionalInt` for primitive results | Write `Optional<Integer>` when `OptionalInt` fits |
Anti-Patterns in Code
The program below shows several of these habits next to better versions. It runs on Java 9 or later.
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class GuidelinesDemo {
static final Map<String, String> EMAILS = Map.of("ada", "[email protected]");
// Good: Optional as a return type
static Optional<String> findEmail(String user) {
return Optional.ofNullable(EMAILS.get(user));
}
// Bad: never return null from an Optional method
// static Optional<String> badFind(String user) { return null; }
// Good: return an empty list, not Optional<List<String>>
static List<String> findOrders(String user) {
return user.equals("ada") ? List.of("order-1") : List.of();
}
// Bad: Optional as a parameter forces callers to wrap values
static String greetBad(Optional<String> name) {
return "Hello, " + name.orElse("guest");
}
// Better: two simple methods (an overload)
static String greet() { return greet("guest"); }
static String greet(String name) { return "Hello, " + name; }
public static void main(String[] args) {
// Anti-pattern: isPresent followed by get
Optional<String> email = findEmail("ada");
if (email.isPresent()) {
System.out.println(email.get());
}
// Better: one clear call
findEmail("ada").ifPresent(System.out::println);
System.out.println(findEmail("bob").orElse("no email")); // no email
System.out.println(findOrders("bob").size()); // 0
System.out.println(greetBad(Optional.of("Lin"))); // Hello, Lin
System.out.println(greet()); // Hello, guest
}
}Here is why each "bad" version causes trouble:
- Returning
nullfrom anOptionalmethod. Callers expect anOptionaland call methods on it. If they getnullinstead, they get aNullPointerException, which is the exact problemOptionalis meant to prevent. isPresent()thenget(). This works, but it is just anullcheck written in a longer way.ifPresent,orElse, andmapsay the same thing more clearly.Optional<List<T>>. An empty list already means "nothing here." Wrapping the list gives callers two kinds of "empty" to check.Optionalparameters. Callers have to wrap every argument, and they can still passnullfor theOptionalitself. Overloads are simpler.
Field and Getter Example
This is the usual way to handle a value that may be missing inside a class:
import java.util.Optional;
public class Person {
private final String nickname; // may be null, kept as a plain field
public Person(String nickname) {
this.nickname = nickname;
}
public Optional<String> getNickname() {
return Optional.ofNullable(nickname);
}
public static void main(String[] args) {
System.out.println(new Person(null).getNickname().orElse("none")); // none
System.out.println(new Person("Ace").getNickname().orElse("none")); // Ace
}
}Exercise
A teammate writes a method Optional<List<String>> findTags(String postId) that returns null when the post has no tags. Name two problems and give a better signature and behavior.
Show answer
First, returning null from a method with an Optional return type can cause a NullPointerException in callers who trust the Optional. Second, wrapping a List in Optional is unneeded, because an empty list already means "no tags." A better version is List<String> findTags(String postId), which returns List.of() when there are no tags.
Exercise
Why is void save(Optional<String> note) considered an anti-pattern, and what is a simpler design?
Show answer
Optional parameters force every caller to wrap values in Optional.of or Optional.empty, and a caller can still pass null for the Optional itself. A simpler design is two overloads, save() and save(String note), or a single method with a plain String parameter that is checked for null.