A wrapper encloses an existing value, object, or dependency and gives it a name and interface that match the meaning the program needs. The point is not extra indirection; it is making an otherwise implicit fact visible in the type system. section 2.6.2 section 10.7
Use a small record when a general representation is too ambiguous. A List field may technically accept mutable lists while the design really requires an immutable value. Wrapping the list as ImmutableList states that requirement at every call site and lets construction copy the input defensively. section 2.6.2
Listing 2.40 Creating immutable list types
record ImmutableList<A>(List<A> items) {
ImmutableList {
items = List.copyOf(items); #A
}
public static <A> ImmutableList<A> of(A... items) { #B
return new ImmutableList<>(List.of(items)); #B
} #B
} This record copies its input, provides a convenient factory, and turns an ordinary List into a type whose name communicates immutable-list semantics. section 2.6.2
Wrappers also capture domain knowledge that would otherwise disappear after a calculation. PastDue wraps an Invoice to distinguish invoices known to be late from arbitrary invoices, even when the wrapped entity remains mutable. Such a wrapper can quarantine awkward legacy identity without pretending its semantics are perfect. section 5.4.1 section 5.4.2
Speak in application terms at a boundary
A database library may require callers to separate inserts from updates. An AccountRepo wrapper can instead offer upsert(List<Account>), own the bucketing logic, and keep the rest of the application independent of the library’s vocabulary. section 10.4.6
Listing 10.41 A wrapper that speaks our semantics
class AccountRepo {
private DatabaseLib databaseLib;
public void upsert(List<Account> accounts) { #A
// bucketing logic...
databaseLib.transact(/*Updates and Inserts*/); #B
}
}The wrapper exposes upsert while hiding the library call that still performs separate update and insert work. section 10.4.6
A useful wrapper should:
- Name a meaningful state, constraint, or operation rather than merely repeat the wrapped API. section 10.7 section 10.4.6
- Enforce self-contained invariants at construction when the required information is available. section 2.6.2 section 5.4.2
- Accept imperfect semantics when stronger validation would require context the type does not own. section 5.4.2
- Contain dependency details so callers work with the program’s data types and vocabulary. section 10.7 section 10.4.6






