Where Optional belongs and where it does not
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Optional was designed for one job: telling the caller of a method that the result may be missing. Used there, it removes a whole class of bugs. Used everywhere else, as fields, parameters or list elements, it adds objects, noise and new ways to fail.
Good use: the return type of a lookup method
A method whose job is to search or look something up may honestly find nothing: findByRoll, findByEmail, findFirstUnpaidFee, parsePincode. For these, a return type of Optional<T> is the right design.
static Map<String, String> hostels = Map.of("21CS042", "Block B, Room 12");
static Optional<String> findHostel(String roll) { // "not found" is a normal outcome return Optional.ofNullable(hostels.get(roll));}
static String roomOf(String roll) { return findHostel(roll).orElse("Day scholar"); // the caller handles the maybe}The caller sees the "maybe" in the signature and handles it with orElse, orElseThrow, map or ifPresentOrElse.
Use it when "not found" is a normal outcome. When a missing value means a bug or bad input that must stop the program, throwing an exception from the method is clearer. When a method always has a result, return the plain type: wrapping a value that is always there only makes callers unwrap it for nothing.
Bad use: fields, parameters and collections of Optional
Fields. An Optional field adds an extra object to every instance, and Optional is not Serializable, so it breaks classes that are saved or sent as bytes. Worse, the field itself can still be null.
Example 1 · Bad: Optional parameter. Good: overloading
import java.util.Optional;
public class OptionalParamDemo { // Bad: every caller must wrap, and null can still sneak in static String badgeBad(String name, Optional<String> nickname) { return name + nickname.map(n -> " (" + n + ")").orElse(""); }
// Good: two overloads, no Optional in the parameters static String badge(String name) { return name; }
static String badge(String name, String nickname) { return name + " (" + nickname + ")"; }
public static void main(String[] args) { System.out.println(badgeBad("Asha", Optional.of("Ashu"))); System.out.println(badgeBad("Bilal", Optional.empty())); try { System.out.println(badgeBad("Chitra", null)); } catch (NullPointerException e) { System.out.println("badgeBad with null: NullPointerException"); }
System.out.println(badge("Asha", "Ashu")); System.out.println(badge("Bilal")); }}Asha (Ashu) Bilal badgeBad with null: NullPointerException Asha (Ashu) Bilal
What this code does
- The
Optionalparameter makes every call longer and still allowsnull, which crashes inside the method: three states instead of two. - Two overloads say the same thing with plain types. A caller with no nickname simply calls the one-argument version.
Example 2 · Bad: Optional field. Good: nullable field, Optional getter
import java.util.List;import java.util.Optional;
class Student { private final String name; private final String email; // may be null: not every student gave one
Student(String name, String email) { this.name = name; this.email = email; }
String getName() { return name; }
Optional<String> getEmail() { // the Optional is created only for the caller return Optional.ofNullable(email); }}
public class OptionalGetterDemo { public static void main(String[] args) { List<Student> batch = List.of( new Student("Deepa", "deepa@college.in"), new Student("Eshan", null), new Student("Fiza", "fiza@college.in"));
for (Student s : batch) { String contact = s.getEmail().orElse("no email, send a letter"); System.out.println(s.getName() + ": " + contact); } long withEmail = batch.stream().filter(s -> s.getEmail().isPresent()).count(); System.out.println(withEmail + " of " + batch.size() + " have email"); }}Deepa: deepa@college.in Eshan: no email, send a letter Fiza: fiza@college.in 2 of 3 have email
What this code does
- The field is a plain
Stringthat may benull. It is private, so only the class itself has to remember that, and it costs no extra object per student. - The getter returns
Optional.ofNullable(email), so callers still get the full benefit: the type tells them the email may be missing.
Keep a normal field that may be null, keep it private, and return Optional.ofNullable(field) from its getter. Parameters. A parameter Optional<String> nickname forces every caller to wrap values with Optional.of(...), and a caller can still pass null, giving three states instead of two. Use two overloaded methods instead, one with and one without the value.
Collections. A List<Optional<T>> or Map<K, Optional<V>> stores "nothing" as an element. Leave the missing items out of the list and the missing keys out of the map; they already have a way to say "not here".
Return an empty list, not an Optional of a list
A method like findOrders(customer) that may find no orders should return an empty list, List.of(), not Optional<List<Order>>. An empty list already means "nothing found", and every caller can loop over it, count it or stream it with no special case.
Example 3 · Return an empty list, not Optional<List>
import java.util.List;import java.util.Map;import java.util.Optional;
public class EmptyListDemo { static Map<String, List<String>> ordersOf = Map.of( "Gopal", List.of("Pen drive", "Mouse"), "Hema", List.of());
// Bad: two kinds of "nothing" static Optional<List<String>> findOrdersBad(String customer) { return Optional.ofNullable(ordersOf.get(customer)); }
// Good: an empty list already means "nothing" static List<String> findOrders(String customer) { return ordersOf.getOrDefault(customer, List.of()); }
public static void main(String[] args) { for (String c : List.of("Gopal", "Hema", "Irfan")) { System.out.println(c + " bad: " + findOrdersBad(c)); } for (String c : List.of("Gopal", "Hema", "Irfan")) { List<String> orders = findOrders(c); System.out.println(c + " good: " + orders.size() + " order(s) " + orders); } }}Gopal bad: Optional[[Pen drive, Mouse]] Hema bad: Optional[[]] Irfan bad: Optional.empty Gopal good: 2 order(s) [Pen drive, Mouse] Hema good: 0 order(s) [] Irfan good: 0 order(s) []
What this code does
- The bad version returns
Optional[[]]for Hema andOptional.emptyfor Irfan. Both mean "no orders", but every caller has to handle them separately. - The good version returns an empty list for both.
size(), loops and streams work on it directly, with no special case.
Optional<List<Order>> creates two different kinds of nothing: Optional.empty and Optional[[]]. Every caller must now unwrap the Optional and still handle the empty list. The same rule applies to arrays, sets, maps and streams: return the empty one.
Trap: returning null from a method that returns Optional
The compiler allows return null; in a method declared to return Optional<T>, because Optional is a normal reference type. It is the worst possible result: callers trust the type and write findCoupon(code).orElse(0), which throws a NullPointerException on the Optional itself.
Example 4 · Trap: return null from an Optional method
import java.util.Optional;
public class ReturnNullTrapDemo { static Optional<Integer> findCouponBad(String code) { if (code.equals("DIWALI50")) { return Optional.of(50); } return null; // compiles, and breaks every caller }
static Optional<Integer> findCoupon(String code) { if (code.equals("DIWALI50")) { return Optional.of(50); } return Optional.empty(); }
public static void main(String[] args) { System.out.println("DIWALI50: " + findCouponBad("DIWALI50").orElse(0)); try { System.out.println("HOLI10: " + findCouponBad("HOLI10").orElse(0)); } catch (NullPointerException e) { System.out.println("HOLI10: NullPointerException from the Optional itself"); } System.out.println("HOLI10 fixed: " + findCoupon("HOLI10").orElse(0)); }}DIWALI50: 50 HOLI10: NullPointerException from the Optional itself HOLI10 fixed: 0
What this code does
return null;compiles becauseOptionalis an ordinary class. The caller trusts the type and callsorElseonnull, which throws an NPE, the exact error Optional exists to prevent.- Returning
Optional.empty()on every "not found" path keeps the promise the return type makes.
A method that returns Optional must return Optional.empty() for "nothing", every time, on every path. The same goes for variables: never assign null to an Optional variable; use Optional.empty().
Why isPresent then get is avoided
if (opt.isPresent()) { use(opt.get()); } is a null check with more typing. It also leaves a bare get() in the code, which crashes the day someone moves it outside the if. Code reviewers flag it as "Optional used like a nullable reference".
Example 5 · Refactoring isPresent then get
import java.util.Optional;
public class IsPresentGetDemo { static Optional<String> findHostel(String roll) { return roll.startsWith("H") ? Optional.of("Block " + roll.charAt(1)) : Optional.empty(); }
public static void main(String[] args) { String roll = "D21";
// Before: the isPresent then get pattern Optional<String> h = findHostel(roll); String before; if (h.isPresent()) { before = h.get().toUpperCase(); } else { before = "DAY SCHOLAR"; } System.out.println("before: " + before);
// After: no get(), one expression String after = findHostel(roll).map(String::toUpperCase).orElse("DAY SCHOLAR"); System.out.println("after: " + after);
// Before / after for "do something only if present" Optional<String> h2 = findHostel("H3X"); if (h2.isPresent()) { System.out.println("before: mess card for " + h2.get()); } findHostel("H3X").ifPresent(b -> System.out.println("after: mess card for " + b)); }}before: DAY SCHOLAR after: DAY SCHOLAR before: mess card for Block 3 after: mess card for Block 3
What this code does
- Both versions give the same results, but the "after" lines have no
get()that could ever be reached on an empty Optional. - The pattern "if present transform, else default" becomes
map(...).orElse(...); "if present act" becomesifPresent(...).
Each shape of that pattern has a direct replacement that has no get() at all:
- if present use it, else a default →
orElse(default)ororElseGet(...). - if present use it, else throw →
orElseThrow(() -> new XException(...)). - if present do something, else nothing →
ifPresent(...); with an else branch →ifPresentOrElse(...). - if present transform it →
map(...), then one of the above.
Next step
Check your understanding
12 quick questions