Card 07/ 08
All 8 cards
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.
// 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> — not finding one is a normal outcome |
| 2 | No | List<Invoice>, empty when there are none |
| 3 | No | Customer — creation either works or throws |
| 4 | Yes | Optional<String> — plenty of people have no middle name |
| 5 | Yes | Optional<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.