Card 07/ 08
Practice: Deciding Which Methods Should Return an Optional
Five signatures; for each, Optional or not, and what it should return otherwise.
Optional belongs on a return type where finding nothing is a normal outcome, and nowhere else. For each of the five signatures below, decide whether it should return an Optional, and what it should return otherwise, all five before opening the answer.
// 1
Customer findByReference(String ref)
// 2
List<Invoice> invoicesFor(Customer c)
// 3
Customer create(NewCustomer details)
// 4
String middleName()
// 5
Invoice mostOverdue(List<Invoice> invoices)Which of the five should return an Optional?
| Optional? | Return | |
|---|---|---|
| 1 | Yes | Optional<Customer>, because not finding one is a normal outcome |
| 2 | No | List<Invoice>, empty when there are none |
| 3 | No | Customer, because creation either works or throws |
| 4 | Yes | Optional<String>, because plenty of people have no middle name |
| 5 | Yes | Optional<Invoice>, because an empty list has no most-overdue invoice |
Number two is the one to argue with. An empty list already means "nothing here", so wrapping it gives the caller two ways to say the same thing and forces them to handle both.
Number three is the other useful one. Absence is not an outcome of creating something: either it worked or something failed, and a failure is an exception rather than an empty container.
← → move through sections and cards