Optional represents either a present non-null value or absence. It makes a hidden branch explicit: an enriched customer may or may not have an approval, which is created lazily. section 6.3.4
Use Optional interactions to express what should happen in both states:
- Use map to transform a present value while preserving absence, then orElse to supply a default. section 6.3.5
- Use isEmpty and get when the surrounding decision is clearer imperatively; functional style is not automatically better. section 6.3.5
- Model business outcomes directly: an absent approval produces NeedsApproval, while approval status determines whether a draft is billable or not billable. section 6.3.5
Assessing a draft with an optional approval
After checking fee thresholds, draft.customer().approval().map(approval -> switch (approval.status()) { ... }).orElse(new NeedsApproval(draft)) keeps the missing-approval case beside the present-value cases. The same decision can be written with isEmpty and get when that better focuses the reader's attention. section 6.3.5
Listing 6.47 Comparing imperative and functional interactions
String imperativeExample(String thingId) {
Optional<String> maybeThing = this.tryToFindThing(thingId);
return maybeThing.isPresent() #A
? maybeThing.get().toUpperCase() #B
: "Default thing!";
}
String functionalExample(String thingId) {
return this.tryToFindThing(thingId) #C
.map(String::toUpperCase) #C
.orElse("Default thing!"); #C
}Compare equivalent imperative and functional Optional code: one inspects presence explicitly, while the other maps a present value and supplies a default. section 6.3.5
Optional can also act as its own transformation space. Data and functions move into it through operations such as Optional.of and lift, allowing algebraic operators to work with optional values; proving the resulting properties remains an exercise. section 7.12 section 7.8.3











