Sub topic 13
Using Optional Well: Guidelines and Anti-Patterns
You now know every main tool that Optional offers. This last chapter covers when to use those tools and when to leave them alone. Optional works well in some places and makes code worse in others.
An anti-pattern is a habit that looks helpful but causes problems. A guideline is a rule of thumb that most experienced Java developers follow. The guidelines here come from the people who designed Optional. They built it for one main job: to be the return type of a method that might have no result. A return type is the kind of value a method gives back.
The Main Rule: Use Optional for Return Values
When a method might not find anything, return Optional<T>. The method's signature then tells the caller "there may be no answer here." The caller cannot forget to handle that case, because the value has to be unwrapped before it can be used.
import java.util.Map;
import java.util.Optional;
public class ReturnTypeDemo {
static final Map<String, String> EMAILS = Map.of("ada", "[email protected]");
// Good: the return type says "maybe there is no email"
static Optional<String> findEmail(String user) {
return Optional.ofNullable(EMAILS.get(user));
}
public static void main(String[] args) {
System.out.println(findEmail("ada").orElse("no email")); // [email protected]
System.out.println(findEmail("bob").orElse("no email")); // no email
}
}The diagram below sums up where Optional belongs. Use it as a quick check when you write a new method or class.
Anti-Pattern 1: Returning null from an Optional Method
A method that returns Optional must never return null. Callers trust the type. They will call .map or .orElse on the result right away, and if the result is null they get a NullPointerException. That is exactly what Optional was meant to stop.
import java.util.Optional;
public class NeverNullDemo {
// Bad: breaks the promise of the return type
static Optional<String> badLookup(boolean found) {
if (!found) {
return null;
}
return Optional.of("value");
}
// Good: return an empty Optional instead
static Optional<String> goodLookup(boolean found) {
return found ? Optional.of("value") : Optional.empty();
}
public static void main(String[] args) {
System.out.println(goodLookup(false).orElse("none")); // none
try {
badLookup(false).orElse("none");
} catch (NullPointerException e) {
System.out.println("badLookup crashed the caller");
}
}
}Anti-Pattern 2: isPresent Followed by get
Beginners often write this:
if (opt.isPresent()) {
System.out.println(opt.get());
}It works, but it is just a null check written a longer way. It also invites mistakes. If someone later deletes the if, get() throws NoSuchElementException on an empty Optional. The methods from earlier chapters say the same thing more clearly.
import java.util.Optional;
public class AvoidGetDemo {
public static void main(String[] args) {
Optional<String> opt = Optional.of("Ada");
// Instead of isPresent + get for an action:
opt.ifPresent(name -> System.out.println("Hi " + name));
// Instead of isPresent + get for a value with a fallback:
String name = opt.orElse("guest");
System.out.println(name);
// When a missing value is a real error, say so clearly.
// orElseThrow() with no arguments was added in Java 10.
String required = opt.orElseThrow();
System.out.println(required);
}
}The no-argument orElseThrow() does the same thing as get(). Its name tells the reader that it can throw, so many teams prefer it over get().
Anti-Pattern 3: Optional as a Field
A field is a variable that belongs to an object. Do not declare fields as Optional. Here is why:
Optionaldoes not implementSerializable. Serializable is a Java interface that lets an object be saved to bytes. A class with anOptionalfield cannot be serialized the standard way.- Each
Optionalis an extra object in memory. - Many frameworks that read fields, such as some JSON and database libraries, do not expect
Optional.
A better approach is to keep a plain field that may be null and return an Optional from the getter. A getter is a method that reads a field.
import java.util.Optional;
public class FieldDemo {
static class Person {
private final String name;
private final String nickname; // may be null, and that is fine inside the class
Person(String name, String nickname) {
this.name = name;
this.nickname = nickname;
}
String getName() {
return name;
}
// The getter is the public API, so it uses Optional
Optional<String> getNickname() {
return Optional.ofNullable(nickname);
}
}
public static void main(String[] args) {
Person p1 = new Person("Margaret", "Peggy");
Person p2 = new Person("Alan", null);
System.out.println(p1.getNickname().orElse(p1.getName())); // Peggy
System.out.println(p2.getNickname().orElse(p2.getName())); // Alan
}
}The null stays inside the class, where the author controls it. Outside code only ever sees an Optional.
Anti-Pattern 4: Optional as a Method Parameter
A parameter is an input to a method. A parameter of type Optional makes every caller wrap their argument, and the caller can still pass null for the Optional itself. The method then has to deal with three cases (a value, empty, and null) where it used to have two.
Use method overloading instead. Overloading means writing two methods with the same name but different parameters.
public class ParameterDemo {
// Bad: static String greet(String name, Optional<String> title)
// Good: two clear versions
static String greet(String name) {
return "Hello, " + name;
}
static String greet(String name, String title) {
return "Hello, " + title + " " + name;
}
public static void main(String[] args) {
System.out.println(greet("Lin")); // Hello, Lin
System.out.println(greet("Lin", "Dr.")); // Hello, Dr. Lin
}
}When overloading would create too many versions, a nullable parameter with clear documentation is still better than an Optional parameter.
Anti-Pattern 5: Optional Around a Collection
Do not return Optional<List<T>>. A list already has a way to say "nothing here": it can be empty. Wrapping it adds a second kind of "nothing," and callers must check both. The same applies to sets, maps, arrays, and streams.
import java.util.List;
import java.util.Map;
public class CollectionDemo {
static final Map<String, List<String>> ORDERS = Map.of("ada", List.of("book", "pen"));
// Good: return an empty list, not Optional<List<String>>
static List<String> ordersFor(String user) {
return ORDERS.getOrDefault(user, List.of());
}
public static void main(String[] args) {
System.out.println(ordersFor("ada").size()); // 2
System.out.println(ordersFor("bob").size()); // 0
for (String item : ordersFor("bob")) {
System.out.println(item); // never runs, and no crash
}
}
}Avoid putting Optional objects inside collections too, as in List<Optional<String>>. Keep only the present values. The Optional::stream trick from the previous chapter does this for you.
More Guidelines
Use Optional.ofNullable for values you do not control
Optional.of(x) throws right away if x is null. Use it only when you are sure the value exists, such as a string literal. For results of map lookups, environment variables, or older APIs, use Optional.ofNullable.
Pick orElseGet for costly defaults
As you saw earlier, orElse always evaluates its argument, even when the Optional holds a value. If the default needs a database call, a big calculation, or a new object, use orElseGet so the work only happens when it is needed.
Do not use Optional only to replace a simple if
Wrapping a value just to call ifPresent on it can make plain code harder to read.
// Overdone
Optional.ofNullable(name).ifPresent(n -> System.out.println(n));
// Clearer
if (name != null) {
System.out.println(name);
}Optional is most useful at the boundary between a method and its caller. Inside a short method, a normal null check is often fine.
Prefer primitive Optionals for numbers
For int, long, and double results, OptionalInt, OptionalLong, and OptionalDouble skip the boxing step. Boxing means wrapping a primitive number in an object such as Integer.
Do not compare Optionals with == or lock on them
Optional is a value-based class. Two Optional objects holding equal values may or may not be the same object. Compare them with equals, never with ==, and never use one in a synchronized block.
import java.util.Optional;
public class EqualsDemo {
public static void main(String[] args) {
Optional<String> a = Optional.of("x");
Optional<String> b = Optional.of("x");
System.out.println(a.equals(b)); // true
System.out.println(Optional.empty().equals(Optional.empty())); // true
}
}Quick Reference
| Situation | Do this | Avoid this |
|---|---|---|
| Method may have no result | Return `Optional<T>` | Return `null` |
| Optional method finds nothing | `return Optional.empty();` | `return null;` |
| Reading the value | `orElse`, `orElseGet`, `orElseThrow`, `ifPresent` | `isPresent()` then `get()` |
| Field that may be missing | Nullable field plus an `Optional` getter | `Optional` field |
| Input that may be missing | Overloaded methods | `Optional` parameter |
| No items to return | Empty collection | `Optional<List<T>>` |
| Value might be `null` | `Optional.ofNullable(x)` | `Optional.of(x)` |
| Expensive default | `orElseGet(() -> ...)` | `orElse(expensive())` |
| Comparing two Optionals | `equals` | `==` |
Exercises
Exercise
A method has the signature Optional<User> findUser(String id). On a cache miss, it runs return null;. What goes wrong, and how do you fix it?
Show answer
Callers trust the return type and call methods such as orElse or map on the result right away, so a null result throws a NullPointerException. Fix it by returning Optional.empty() when no user is found.
Exercise
Rewrite this code without using get(): if (opt.isPresent()) { label = opt.get(); } else { label = "none"; }
Show answer
String label = opt.orElse("none");
Exercise
A class has the field private Optional<String> middleName;. Give two reasons this is a poor choice, and describe a better design.
Show answer
Optional is not Serializable, and each field value costs an extra object. Some frameworks also do not handle Optional fields. A better design uses a plain private String middleName; that may be null, plus a getter Optional<String> getMiddleName() { return Optional.ofNullable(middleName); }.
Exercise
Should a method that searches for products return Optional<List<Product>> or List<Product>? Why?
Show answer
It should return List<Product>. An empty list already means "no products," so wrapping it in Optional adds a second way to say "nothing" that callers would have to check as well.
Exercise
You want a method that sends a message with an optional subject line. Why is send(String body, Optional<String> subject) a weak design, and what is a better one?
Show answer
Every caller has to wrap the subject, and a caller could still pass null for the Optional, which leaves three cases to handle. A better design overloads the method: send(String body) and send(String body, String subject).