Card 02/ 08
Optional Example: A Lookup Before and After
The same lookup returning null and returning an Optional, with the same call site in both.
Rewriting a lookup that returns null so that it returns Optional removes the null check from every caller. The same lookup, first returning null:
Customer findByReference(String ref) {
return byRef.get(ref);
}
Customer c = findByReference(ref);
String label = c.name().toUpperCase();And returning an Optional:
Optional<Customer> findByReference(String ref) {
return Optional.ofNullable(byRef.get(ref));
}
String label = findByReference(ref)
.map(Customer::name)
.map(String::toUpperCase)
.orElse("UNKNOWN");map here is the method on Optional, not the stream operation with the same name, and it follows the same rule: apply the function to the value if there is one, and pass the emptiness along if there is not.
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.
← → move through sections and cards