ExerciseDifficulty: Advanced1 min

Five Signatures: Which Should Return an Optional

Five method signatures. For each, decide whether returning an Optional is right, and say what it should return otherwise. All five before the reveal.

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> — not finding one is a normal outcome
2NoList<Invoice>, empty when there are none
3NoCustomer — creation either works or throws
4YesOptional<String> — plenty of people have no middle name
5YesOptional<Invoice> — 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.