liveBook · Manning

Option

As explained in Data-Oriented Programming in Java

Optional is the Java container class that represents either a present non-null value or the absence of a value.

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

How Data-Oriented Programming in Java covers it

How deep it goes
Descends from presence checks and transformations to lifted algebra, but defers proving the resulting properties.
Examples
Uses customer approvals, uppercase defaults, generic Optional arguments, and lifted policy, finding, and status operators.
What you can do after
Apply it via map, orElse, isEmpty, get, Optional.of, and lifted operators to represent absence and compose behavior.
How it connects
Connects optional values to functional transformations, lifting, binary operators, and algebraic properties.

Also explained in

Compare how 12 books explain option →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming in Java. The section links point to the parts of the book it draws on.