Workbench / Volume 3 Companion: The Backend
V3·34
OOP and Its Alternatives
Companion to Volume 3, chapter 34: how encapsulation, polymorphism, composition, pattern matching and value semantics connect; new angles (the expression problem as a spreadsheet you can extend by rows or by columns, a golden master as a photograph before renovation, a record's equality as a fingerprint of its contents); what the chapter simplifies, measured on JDK 21 and the build's stage 35: what a sealed type's compiler errors find and what they can't, a record whose hash changed while it sat in a HashSet, and record equality that disagrees with == for NaN and -0.0; the theory behind subtyping and algebraic data types; how OpenJDK generates a record's equals and hashCode at run time; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 34 has five parts: what OOP is for (the problem objects solve, other paradigms), the four pillars (encapsulation, abstraction, inheritance, polymorphism, dispatch beyond single receivers, the expression problem), relationships between objects (association to composition, composition over inheritance, Liskov substitution), values and identity (object identity, value objects, immutability) and paradigms side by side.
The links worth remembering:
- Encapsulation is about invariants, not getters. An object earns its keep when it makes an invalid state impossible to reach (an
OrderLinewith quantity 0 can't exist). Fields behind getters and setters with no rules is a struct with ceremony. - The expression problem decides the shape. Virtual methods make new types cheap and new operations expensive; sealed data with pattern matching makes the opposite trade. Most systems use both: data for a closed domain, interfaces at open boundaries.
- Value or entity is a modelling decision with consequences for equality. Values are equal by contents and best immutable; entities are equal by identity and change over time. Mixing them (a mutable object in a
HashSet) is where equality bugs live.
Explain it differently
1. The expression problem is a spreadsheet. Rows are types (events), columns are operations (transition, label, serialise). Object-oriented code stores the sheet by rows: adding a row is one class, adding a column touches every class. Functional code stores it by columns: adding a column is one function, adding a row touches every function. Stage 35 added a row and the compiler listed four cells.
2. Inheritance is a building where floors share load-bearing walls. You can add a floor (a subclass) quickly, but changing a wall on the ground floor (a base class method) can bring down floors you didn't know about: the fragile base class.
3. Composition is furniture. Objects that hold other objects can swap them without rebuilding the room: a Server that holds a list of Routes can change its routes without changing its class.
4. Liskov substitution is a stand-in actor. A stand-in must be able to play every scene the lead plays, with no surprises for the other actors. A Square that refuses to change only its width isn't a stand-in for a Rectangle.
5. A record's equality is a fingerprint of its contents. Same contents, same fingerprint. But if one of the contents is a mutable list and the list changes, the fingerprint changes too, while the record sits in a set filed under its old fingerprint.
6. A golden master is a photograph of the house before renovation. You don't need to know why each thing is where it is; you only need to see afterwards whether anything moved. The hard part is deciding what may legitimately differ (the time on the clock in the photo).
7. Pattern matching is a sorting office with a slot for every kind of parcel. A sealed type tells the office every kind that exists, so it can refuse to open until every kind has a slot.
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from OpenJDK 21.0.12 and the build's stage 35 (exp/35), unless stated.
1. Exhaustive switches find the places that are modelled, and only those. The chapter shows sealed types making the compiler check every case. Adding KitchenDelayed to TiffinBox's sealed OrderEvent:
core/src/in/tiffinbox/core/Transition.java:19: error: the switch expression does not cover all possible input values
core/src/in/tiffinbox/core/Transition.java:27: error: the switch expression does not cover all possible input values
core/src/in/tiffinbox/core/Transition.java:34: error: the switch expression does not cover all possible input values
core/src/in/tiffinbox/core/Transition.java:41: error: the switch expression does not cover all possible input values
4 errors
Four precise places. But three more places had to change, and the compiler said nothing about them: the server's command parser (a string switch with a default), the lifecycle specification table (a test, which failed: expected: <36> but was: <30>), and an invariant that assumed every transition moved forward (which failed for the wrong reason). And the contract didn't change at all: the order's JSON has no prep time, so the delay is invisible to clients. Exhaustiveness checks a type's consumers in the same compilation; strings, data formats, other services and tests are outside it.
2. A record makes equality correct, not safe. The chapter presents records as value objects with generated equals and hashCode. With a mutable component:
true -813607908
false 449637052 1 true
A Line record holding an ArrayList was put in a HashSet; contains with an equal record was true. Then the list was mutated: the record's hash changed (-813607908 to 449637052), and set.contains(l) became false, although the set's only element equals(l). The record is shallowly immutable: its fields can't be reassigned, but what they point to can change. Copy defensively in the compact constructor (notes = List.copyOf(notes)), as TiffinBox's Order does.
3. Record equality isn't == on each field. For double components:
true false false true
new Price(NaN).equals(new Price(NaN)) is true while NaN == NaN is false; new Price(0.0).equals(new Price(-0.0)) is false while 0.0 == -0.0 is true. Records compare floating-point components like Double.compare, bit-wise in effect, so that equals is reflexive (a NaN-holding record equals itself) and consistent with hashCode. Code that compares a record's fields by hand with == and the record's own equals can disagree; for money this is one more reason not to use double.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "Sealed types tell you every place to change." | Only switches in the same compilation; strings, tests and contracts aren't checked. |
Gaps 1 |
| "Records are immutable." | Shallowly: a mutable component can change and move the hash. | Gaps 2 |
| "Record equals is field-by-field ==." | Doubles compare like Double.compare: NaN equals NaN, 0.0 differs from -0.0. |
Gaps 3 |
| "Refactoring is safe if the tests pass." | Tests check what they assert; a golden master checks everything it recorded. | Stage 35, step 1 |
| "Inheritance is for reuse." | Composition reuses without the fragile base class; inherit for substitutability. | Explain it differently 2 |
| "OOP and pattern matching are rival styles." | Most systems need both: data for closed domains, interfaces at open boundaries. | ADR-0037 |
| "A failing test after a valid change means the change is wrong." | Sometimes the test encoded an assumption, not the rule. | Stage 35, step 4 |
Theoretical gaps: the ideas behind the chapter
1. Algebraic data types. A sealed interface of records is a sum of products: an OrderEvent is one of six variants, each a product of fields. Pattern matching is the elimination form; exhaustiveness is the compiler checking the sum. ML and Haskell had this in the 1970s and 80s; Java added it in 17–21.
2. Behavioural subtyping. Liskov and Wing (1994): a subtype must accept every input its supertype accepts (preconditions no stronger), guarantee what it guarantees (postconditions no weaker) and keep its invariants. It's a rule about specifications, which is why the compiler can't check it.
3. The expression problem, named. Philip Wadler (1998): add both new cases and new functions without recompiling existing code, with static type safety. Solutions include visitors (OOP), type classes (Haskell), multimethods (CLOS, Clojure), and object algebras.
4. Identity, state and value. Rich Hickey's distinction: an identity is a stable logical entity associated with a series of values over time; state is the value at a moment. TiffinBox's Order follows it: an id, and a new immutable record per state.
5. Characterisation tests. Michael Feathers' Working Effectively with Legacy Code: before changing code you don't understand, write tests that capture what it does, not what it should do. A golden master is the coarse-grained version.
Applying it
Code walkthrough
Gaps 2 and 3 are explained by how a record's equals and hashCode exist at all: they aren't compiled into the class as bytecode loops; the compiler emits an invokedynamic that calls java.lang.runtime.ObjectMethods.bootstrap, which builds them from method handles the first time they're used. From openjdk/jdk21u, src/java.base/share/classes/java/lang/runtime/ObjectMethods.java.
equals, assembled from guards
private static MethodHandle makeEquals(Class<?> receiverClass,
List<MethodHandle> getters) {
MethodType rr = MethodType.methodType(boolean.class, receiverClass, receiverClass);
MethodType ro = MethodType.methodType(boolean.class, receiverClass, Object.class);
MethodHandle instanceFalse = MethodHandles.dropArguments(FALSE, 0, receiverClass, Object.class); // (RO)Z
MethodHandle instanceTrue = MethodHandles.dropArguments(TRUE, 0, receiverClass, Object.class); // (RO)Z
MethodHandle isSameObject = OBJECT_EQ.asType(ro); // (RO)Z
MethodHandle isInstance = MethodHandles.dropArguments(CLASS_IS_INSTANCE.bindTo(receiverClass), 0, receiverClass); // (RO)Z
MethodHandle accumulator = MethodHandles.dropArguments(TRUE, 0, receiverClass, receiverClass); // (RR)Z
for (MethodHandle getter : getters) {
MethodHandle equalator = equalator(getter.type().returnType()); // (TT)Z
MethodHandle thisFieldEqual = MethodHandles.filterArguments(equalator, 0, getter, getter); // (RR)Z
accumulator = MethodHandles.guardWithTest(thisFieldEqual, accumulator, instanceFalse.asType(rr));
}
return MethodHandles.guardWithTest(isSameObject,
instanceTrue,
MethodHandles.guardWithTest(isInstance, accumulator.asType(ro), instanceFalse));
}
Read it from the bottom: same object, true; not an instance of this record class, false; otherwise compare each component with its "equalator", stopping at the first difference. It's a chain of method handles the JIT can inline like hand-written code. Note isInstance: a record is final, so there's no subclass to worry about, which is why records avoid the chapter's "equals with inheritance" trap (P3).
What "equal" means per component
private static MethodHandle equalator(Class<?> clazz) {
return (clazz.isPrimitive()
? primitiveEquals.get(clazz)
: OBJECTS_EQUALS.asType(MethodType.methodType(boolean.class, clazz, clazz)));
}
Reference components use Objects.equals (so a mutable List is compared by its current contents: Gaps 2). Primitive components use a per-type table; for float and double it compares like Float.compare/Double.compare, which is why NaN equals NaN and 0.0 differs from -0.0 (Gaps 3).
hashCode, combined like everyone else's
private static int hashCombiner(int x, int y) {
return x*31 + y;
}
The familiar 31 * h + field from Objects.hash and List.hashCode, applied component by component: the hash depends on every component's current hash, so a mutated list changes the record's hash.
Debugging drills
D1. A new event that "does nothing"
A developer adds a KitchenPaused event to the sealed type, implements it in Transition, and every test passes. In production, tapping Pause returns unknown event.
D2. Duplicate notes in a set
A deduplication step puts order lines in a HashSet, then appends a note to one of them; later the set holds two "equal" lines.
D3. A refactor that changed one response
After moving routes into a table, the golden master shows one difference: GET /kitchen/connection.js now returns the kitchen page HTML instead of the script.
D4. Square and Rectangle in the pricing rules
A BulkDiscount extends PercentOff overrides apply to give a larger discount above a quantity; a report that sums "percentage discounts" double-counts some orders.
Career-oriented
Interview prep
Mid-level 1: composition or inheritance?
Question. "When would you use inheritance instead of composition?"
How to get there. State the default, then the cases where inheritance earns its place, then the risks.
Mid-level 2: value object or entity?
Question. "Is a customer's address a value object or an entity? How would you implement it?"
How to get there. Identity over time, then equality, then mutability.
Senior 1: adding a case safely
Question. "Our payment service needs a new payment method. How do you make sure nothing is missed?"
How to get there. Make the compiler, the tests and the contract find the places.
Senior 2: refactoring a god class
Question. "A 3,000-line class handles HTTP, business rules and persistence. How do you split it without breaking things?"
How to get there. Safety net first, then small moves, then boundaries.
Staff 1: a modelling style for the organisation
Question. "Teams argue about OOP versus functional style in Java. What guidance do you give?"
How to get there. Tie the choice to the kind of change each part of the system sees.
Staff 2: domain modelling across services
Question. "Two services both have an Order, with different fields and rules. Should we unify them?"
How to get there. Bounded contexts, the cost of sharing, and how they communicate.