Volume 3 Exercises: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Exercises: The Backend

V3·34

Object-Oriented Programming

Exercises for Volume 3, chapter 34: what objects solve and when not to use them; encapsulation, abstraction, inheritance and polymorphism; dispatch (static and dynamic, single and double); the expression problem; association, aggregation, composition and dependency; composition over inheritance; Liskov substitution; identity, value objects and immutability; and OOP compared with data-plus-pattern-matching in Java, Go, Rust and Python. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~13 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The four sets and the locking work as before. Code is in Java 21, with Go 1.24, Rust 1.97 and Python 3 for comparison. Every quoted output is real and was measured for these exercises. Five of them catch experienced developers:

  • P1: a superclass constructor called an overridden method, and the subclass saw its own final field as null.
  • P2: pay(o) with Object o = "upi" chose pay(Object), not pay(String). ab.name read the superclass's field even though ab was a B.
  • P3: a ColorPoint subclass broke equals symmetry. p.equals(cp) was true and cp.equals(p) was false, so HashSet.contains depended on which object you asked about.
  • P5: a getter returned the internal list, so a "maximum 3 items" cart held 5.
  • P8: in Go, an error that was a nil pointer still compared as err == nil → false.

The chapter's lab showed four results:

  • the fragile base class: CountingSet counted 6 instead of 3;
  • a mutable HashMap key that get couldn't find even with the original object;
  • the Square/Rectangle violation of Liskov substitution: area 16 instead of 20;
  • equals without hashCode: a set held two equal dishes.

The exercises build on those results and don't repeat them. TiffinBox's order and payment domain is the running example, with money in paise.

Coverage map.

Chapter component Exercises
what objects solve; other paradigms T1, P9
encapsulation T2, P5
abstraction T2, P6
inheritance; composition over inheritance; fragile base class T3, P1, P6
polymorphism; static and dynamic dispatch T4, P2, P7
dispatch beyond single receivers; double dispatch T4, P6
the expression problem T5, P6
association, aggregation, composition, dependency T6
Liskov substitution T7, P3
identity, value objects, immutability; equals contracts T8, P3, P4
paradigms side by side T9, P8, P9

Theory

T1. What objects are for, and when not to use them

  1. State the problem objects solve: keeping data and the rules that protect it together, so invalid states can't be created. Give three TiffinBox examples where that matters (an Order that can't be accepted twice, a Wallet balance that can't go negative, a Coupon that can't be applied after expiry).
  2. Name three kinds of backend code where classic OOP is the wrong default, and what fits better: - DTOs and API payloads; - data transformations and reports; - stateless request handlers.
  3. Compare the paradigms the chapter lists (procedural, object-oriented, functional, data-oriented) by asking: where do the rules live, and what changes are cheap?

T2. Encapsulation and abstraction

  1. Encapsulation is more than private fields. Explain: - invariants; - "tell, don't ask"; - leaking internals through getters (P5: a returned list let a 3-item cart hold 5); - why getters and setters for every field are not encapsulation.
  2. Abstraction means exposing what and hiding how. Design the PaymentGateway abstraction for TiffinBox so that Razorpay, a fake for tests and a future Stripe adapter all fit it. Which details must not leak through it (HTTP, retries, provider error codes)?
  3. Explain how package-private visibility and modules (ch33's T8) extend encapsulation from one class to a whole feature.

T3. Inheritance and composition

  1. The lab's fragile base class (CountingSet counted 6 instead of 3) and P1 (an overridden method called from the superclass constructor saw name = null) are two ways inheritance couples a subclass to its parent's implementation. Explain both, and Bloch's rule: "design and document for inheritance or else prohibit it".
  2. Rewrite an inheritance hierarchy as composition:

    Text
    BaseNotifier
    ├── SmsNotifier
    │   └── RetryingSmsNotifier
    └── WhatsAppNotifier
        └── RetryingLoggingWhatsAppNotifier
    

Use decorators, which give you combinations without a class for each one. 3. When is inheritance the right tool? Consider framework base classes, template methods, sealed hierarchies of data, and exceptions.

T4. Polymorphism and dispatch

  1. P2 measured three things. Overload resolution is static: pay(o) with Object o = "upi" called pay(Object). Overriding is dynamic: ab.me() called B.method. Fields and static methods are not polymorphic: ab.name read A.field while ((B) ab).name read B.field. Explain each, with the bug each one causes.
  2. Single dispatch picks the method by the receiver's runtime type only. Explain double dispatch and the Visitor pattern, then compare them with Java 21's pattern matching over sealed types (P6) and with multiple dispatch in languages that have it (Julia, CLOS).
  3. P7 measured the JIT's view of a polymorphic call site: 200 million calls through Rule.apply took 768 ms with 1 implementation, 1,182 ms with 2 and 1,800 ms with 4. Explain monomorphic, bimorphic and megamorphic call sites and inline caches, and say when this matters.

T5. The expression problem

  1. State the expression problem: adding new types and new operations to a system without changing existing code and with static type safety. Show why OOP makes new types cheap and new operations expensive, and why sealed types with pattern matching (or functional languages) make the opposite true.
  2. Apply it to TiffinBox. Payment methods (UPI, card, cash, wallet, pay later) change rarely. Operations on them (fees, refunds, receipts, risk checks, reports) are added often. Which design fits? For "delivery partners" (in-house, Dunzo, Porter, Shadowfax, added per city), which design fits?
  3. Name techniques that partly solve both sides (type classes and traits, visitors with default methods, plugin registries), and say what each gives up.

T6. Relationships between objects

  1. Define these relationships, give a TiffinBox example of each, and show how it appears in code (fields, constructor parameters, method parameters) and in the database (chapter 49): - association; - aggregation; - composition; - dependency.
  2. Composition implies a lifecycle: an Order owns its OrderLines. What does that mean for creating, deleting, transaction boundaries and the aggregate root in domain-driven design?
  3. Explain why bidirectional associations (Order.kitchen and Kitchen.orders) cause problems in object graphs and ORMs (consistency, lazy loading, serialisation cycles), and what to do instead.

T7. Liskov substitution

  1. State the Liskov substitution principle as contracts. A subtype may not strengthen preconditions, weaken postconditions or break invariants, and must not throw new kinds of exceptions callers don't expect. The lab's Square broke Rectangle's postcondition (area 16 instead of 20). P3's ColorPoint broke equals symmetry. Classify both.
  2. Find the Liskov violations: - ReadOnlyOrderRepository extends OrderRepository throws UnsupportedOperationException from save; - Collections.unmodifiableList implements List; - a CachedPricingService that returns prices up to 10 minutes stale; - a PremiumKitchen whose accept also requires a manager approval.
  3. How do you test substitutability? Consider contract tests that run against every implementation, and the ones the JDK itself relies on (EqualsVerifier for equals).

T8. Identity, value objects and immutability

  1. Distinguish entities (identity persists while attributes change: an Order placed, then accepted, then delivered is still order 1042) from value objects (equal by attributes, interchangeable: Money(4000), Address, TimeSlot). How should each implement equals and hashCode? Cover the JPA problem of an entity whose id is null until it's saved.
  2. Immutability. Why do value objects have to be immutable? The lab's mutable HashMap key couldn't be found even with the original object. Which "withers" and builder patterns does Java offer for immutable updates?
  3. Where does mutability belong in a backend (entities, aggregates, caches, builders), and how do you keep it contained?

T9. Paradigms side by side

  1. Implement "a cart can be paid by UPI, card or cash, with different fees and receipt text" in four ways and compare them: - Java OOP (interface plus classes); - Java data-oriented (sealed records plus switch); - Go (an interface satisfied implicitly, plus struct embedding); - Rust (a trait with dyn trait objects, and alternatively an enum with match).
  2. P8 measured Go and Rust details: - Go's embedding promoted Log from Logger to OrderService, and *SMS satisfied Notifier without declaring it. - A function returning a nil *MyErr as error gave err == nil false. - Rust's trait objects and enum gave the same result (40500), and Box<dyn Rule> and the enum were both 16 bytes. - Python's MRO for Curry(Veg, Spicy) was Curry → Veg → Spicy → Item → object, and label() gave veg+spicy+item.

Explain each. 3. What does each language nudge you towards, and what should a Java team borrow from the others?

Programming exercises

P1. Constructors, overridable methods and initialisation order

Reproduce the trap. Base() calls describe(), which Kitchen overrides to print its final String name. Then add static and instance initialisers and print the full order of events for new Kitchen("Asha's"). Fix the design three ways: a final method, a static factory, and composition.

P2. Static versus dynamic dispatch

Show: - an overload chosen by the declared type (pay(Object) versus pay(String)); - overriding by the runtime type; - field hiding (ab.name versus ((B) ab).name); - static method hiding; - the List<Integer>.remove(1) trap; - an equals(Order) overload that HashSet never calls.

Then fix the equals bug and add @Override everywhere it belongs.

P3. Equals contracts with inheritance

Reproduce ColorPoint breaking symmetry, including the HashSet membership results in both directions. Then try the "fix" that ignores colour when comparing with a plain Point, and show it breaks transitivity. Finally, apply the two real fixes: getClass()-based equality, and composition with a Point inside. Check each with EqualsVerifier (Maven: nl.jqno.equalsverifier).

P4. Entities versus value objects

Implement Order as an entity (id-based equality, with an id assigned at creation as a UUIDv7-style time-ordered id) and Money, Address and TimeSlot as value records. Then demonstrate the JPA-style trap: an entity whose hashCode uses an id that is null until "save", put into a HashSet before saving. Show that it gets lost, and fix it.

P5. Encapsulation: closing the leaks

Write a Cart that enforces "at most 3 lines" and "no changes after checkout". Show the leak: a getter returning the internal list lets a caller add 2 more lines. Then close it: - unmodifiable snapshots; - intention-revealing methods; - no setters; - a checkout() that returns an immutable PlacedOrder.

Write tests that try to break each invariant.

P6. The expression problem, both ways

Implement payments (Upi, Card, Cash) with two operations, fee and receipt, in both styles: an interface with classes, and sealed records with switch functions. Then make both changes in each style: - add an operation, riskScore; - add a type, Wallet.

Count the files changed and note what the compiler tells you each time. Finally, write a Visitor version and compare it.

P7. Polymorphic call sites and the JIT

Measure 200 million calls through an interface with 1, 2 and 4 implementations at the same call site, after warm-up. Then repeat with the 2-type array sorted rather than random, to separate branch prediction from megamorphic dispatch. Optionally confirm with -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining, or with JMH.

P8. OOP in Go, Rust and Python

Port the notifier design (Notifier interface, SMS and WhatsApp implementations, retry and logging decorators) to Go and Rust, and the diamond Curry(Veg, Spicy) to Python. Reproduce: - Go embedding and implicit interfaces; - Go's typed-nil error; - Rust dyn versus enum dispatch, including their sizes; - Python's MRO.

Fix the Go typed-nil bug.

P9. Refactor a class hierarchy into data and functions

Start from an Order class hierarchy: Order → DeliveryOrder and PickupOrder → ScheduledDeliveryOrder, with overridden fee(), eta() and label(), plus a boolean isScheduled flag that some methods check. Refactor it to an Order record with a sealed Fulfilment component (Delivery(Address, Optional<TimeSlot>), Pickup(Kitchen)) and functions with exhaustive switches. Compare the line counts, the tests, and how many invalid states each version can represent.

Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–34)

C1. Design the TiffinBox order aggregate

Build the Order aggregate: - the entity (id at creation), with OrderLine composition, value objects (Money, Quantity, Address, TimeSlot) and a sealed Fulfilment; - a status state machine (ch33's P9) with methods that check invariants (accept, markReady, cancel(reason)); - domain events (OrderPlaced, OrderAccepted) recorded by the aggregate; - a repository interface with in-memory and file-backed implementations that pass the same contract tests (T7).

Combines: Volume 1's state machines and data modelling, Volume 2's frontend order states (ch 25), ch33's money, records and enums, and this chapter.

C2. Replace an inheritance-based plugin system with composition

TiffinBox's pricing has BasePricing → FestivalPricing → FestivalWeekendPricing → FestivalWeekendRainPricing, plus copy-pasted variants for each city. Replace it with: - a pipeline of small PricingRule objects (composition); - rule configuration per city loaded from data; - an explanation trail ("₹30 rain surcharge applied"); - property tests showing that the new pipeline matches the old hierarchy on 100,000 random carts before the old code is deleted.

Combines: Volume 1's refactoring and testing, Volume 2's feature flags and configuration (ch 31), ch33's money rules, and this chapter's composition.

C3. A polyglot comparison report

Implement the same small domain (cart, payment alternatives, fee rules, notifier decorators) in Java, Go, Rust and Python (or TypeScript from Volume 2), and write a report comparing: - how each expresses closed versus open sets (T5); - how errors and absence are represented (ch33's T10); - how immutability is achieved; - testing style; - lines of code; - the bugs each language's type system caught during development (keep a log).

Combines: Volume 1's language comparisons, Volume 2's TypeScript discriminated unions (ch 16), ch33's language foundations, and this chapter.

What the chapter leaves out

SOLID beyond Liskov

The chapter covers substitutability. The rest of SOLID is used in design discussions all the time:

  • Single responsibility: a class should have one reason to change.
  • Open/closed: a module is open for extension and closed for modification, which is T5's open-set side.
  • Interface segregation: small interfaces per client, like T7's OrderReader and OrderWriter.
  • Dependency inversion: high-level code depends on abstractions it owns, which is the basis of hexagonal architecture and of dependency injection in chapter 46.

Treat these as heuristics to argue from, not laws.

Design patterns, in modern form

Strategy, Decorator (T3), Adapter (T2's gateway), Factory, Builder, Observer, Template Method, Visitor (T4) and State are named solutions you'll see in code reviews and in framework source. Many shrink to a lambda or a sealed type in modern Java (Strategy becomes a Function; State becomes a sealed type with a switch). Learn the names, which make good shared vocabulary, and prefer the simplest form.

Domain-driven design's tactical patterns

The chapter's values and entities are half of DDD's tactical toolkit. The other half:

  • aggregates with transactional consistency boundaries (T6, C1);
  • domain events;
  • repositories;
  • domain services for logic that doesn't belong to one entity;
  • bounded contexts, where "Order" means different things to the kitchen and to billing.

Chapters 44 and 55 use these for structuring services.

Object lifecycle, proxies and frameworks

Frameworks create objects for you, through dependency injection, JPA entity proxies and Spring AOP proxies. That changes OOP assumptions in four ways:

  • final classes can't be proxied by CGLIB-style subclassing;
  • getClass() in equals breaks with Hibernate proxies (P3);
  • self-invocation bypasses proxies (ch33's P10);
  • constructors may not run the way you expect (JPA needs no-arg constructors).

Chapters 46 and 49 cover the rules. Write classes knowing which framework will instantiate them.

Mixins, traits and default methods

Java's default methods add limited multiple inheritance of behaviour. When two interfaces supply the same default method, the class must override it and choose explicitly; a Curry implements Veg, Spicy that returned Veg.super.label() + "+" + Spicy.super.label() printed veg+spicy (measured on JDK 21), compared with Python's MRO result in P8. Scala traits, Kotlin interface delegation (class Svc(n: Notifier) : Notifier by n) and Python mixins go further. Use default methods for convenience methods built on the abstract ones, not for sharing state or deep hierarchies.

Senior exercises

S1. Write the team's object design guidelines

Write one page that says when to use each of: - classes; - records; - enums; - sealed types; - interfaces; - inheritance.

Also cover how to implement equals for entities and values, rules for constructors and mutability, composition and decorator conventions, and the checks that enforce them (Error Prone, ArchUnit, EqualsVerifier in tests). Tie each rule to an output from these exercises or the lab.

S2. Review a design that misuses inheritance

A pull request introduces: - AbstractEntity with a mutable Long id and equals/hashCode based on it, used by all entities; - Customer extends AbstractEntity and PremiumCustomer extends Customer, which overrides getDiscount() and adds an equals that also compares tier; - OrderService extends BaseService, which provides logging, a cache and a protected repository field; - NotificationSender extends HttpClient.

Write the review.

S3. Decide where a new operation goes: the expression problem in practice

The product team wants "carbon estimate per order", which depends on the fulfilment type (delivery by EV bike, delivery by petrol bike, pickup, scheduled batch delivery). The codebase has sealed Fulfilment records (P9). A teammate proposes adding carbonGrams() to each record. Another proposes a Carbon.estimate(Fulfilment) function in a sustainability module. A third wants a plugin interface so the sustainability team can change the models without touching orders. Decide, and write the reasoning.

S4. Teach composition over inheritance with three outputs

Prepare a 15-minute session for a team that over-uses inheritance. Use: - the lab's CountingSet (6 versus 3); - P1's constructor hook (name = null); - P3's asymmetric equals with HashSet membership both ways.

For each, show the code, ask the room to predict, reveal the output, explain, and then show the composition version. End with three rules.

S5. Lead a modelling session for a new domain

TiffinBox is adding subscriptions: weekly meal plans with skips, pauses, plan changes, prorated refunds and per-day menus. Run a 90-minute modelling session with product and engineering. Produce: - the entities and value objects; - the aggregates and their boundaries; - the sealed alternatives; - the state machine; - which invariants live where; - the open questions.

Write the outcome document.