ExerciseDifficulty: Advanced1 min

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.

java
// 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?
Each signature, the verdict, and what it should return
Optional?Return
1YesOptional<Customer>, because not finding one is a normal outcome
2NoList<Invoice>, empty when there are none
3NoCustomer, because creation either works or throws
4YesOptional<String>, because plenty of people have no middle name
5YesOptional<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.