Card 01/ 08
All 8 cards
ConceptDifficulty: Intermediate1 min
A Return Type That Says There Might Be Nothing Here
A method called findByReference returns a Customer. Whether it can return null is written in the documentation, if anywhere, and the compiler will not help you either way.
Customer findByReference(String ref);
Customer c = findByReference(ref);
System.out.println(c.name());Optional<Customer> moves that fact into the signature. It is a container holding either one value or nothing, and a caller cannot reach the value without acknowledging that it might be absent.
Optional<Customer> findByReference(String ref);
String name = findByReference(ref)
.map(Customer::name)
.orElse("unknown");| Signature says | Caller learns |
|---|---|
Customer | Nothing about absence; must read the documentation or guess |
Optional<Customer> | Absence is expected, and the compiler will not let it be ignored |
So Optional is a documentation mechanism the compiler enforces. It exists for exactly one job — a method saying "there might be nothing to return" in a way a caller cannot miss.