Card 02/ 08
All 8 cards
ExampleDifficulty: Intermediate1 min
A Lookup That Might Not Find Anything, Before and After
The same lookup written twice: once returning null and once returning an Optional, with the same call site in both.
Customer findByReference(String ref) {
return byRef.get(ref);
}
Customer c = findByReference(ref);
String label = c.name().toUpperCase();Optional<Customer> findByReference(String ref) {
return Optional.ofNullable(byRef.get(ref));
}
String label = findByReference(ref)
.map(Customer::name)
.map(String::toUpperCase)
.orElse("UNKNOWN");Optional.ofNullable wraps a value that might be null. map applies a function only when there is a value, so both map calls are skipped when the lookup found nothing, and orElse supplies the answer.
No if and no null check, and no way to reach toUpperCase on nothing. The absence is handled once, at the end, rather than at every step.