JAVA-270 · Lesson 12 of 12 · 28 min
Capstone: redesigning a tangled application
▶ Video coming soon A video version of this lesson is on the way.
The plan for the second half of April 2028 is simple to state. Hamza has eight working evenings, from Tuesday, April 18 to Friday, April 28, to turn CounterApp.java, one class of 1,140 lines with no tests, into a program built the way this course has described: a domain model at the centre, use cases behind ports, adapters around the edge, and a test suite that runs in seconds. On Tuesday, May 2, at 5:00 pm in the back room, he will present the redesign to Ingrid, Leif, Odile and Kofi. If they accept it, the new CounterApp goes onto the counter computer the following Saturday, running beside the old one for two weeks as OrderDesk did. This lesson walks through the plan, the main pieces of the new design and the review, as worked examples you can follow and adapt to a tangled program of your own.
The rule that governs the whole capstone comes from lesson 10: no big rewrite. The shop keeps selling parts and booking repairs every day of those two weeks. Every step must leave a program that works, and every step must be small enough that if something breaks, the cause is obvious.
Step 1: measure the tangle
Lesson 1 measured the cost of Odile's last six requests: an average of 3.7 places edited per change, and half the changes broke something else. Before changing anything, Hamza adds a second measurement, a map of which jobs CounterApp does and how many of its 1,140 lines each job touches. The point is to choose where to start. The best first target is the job that changes most often and is most tangled, because it repays the effort soonest.
import java.util.*;
public class Main {
record Job(String name, int linesTouched, int changesLastYear, boolean hasRulesOdileWantsChanged) {
int priority() { return changesLastYear * 10 + (hasRulesOdileWantsChanged ? 25 : 0) + linesTouched / 20; }
}
public static void main(String[] args) {
List<Job> jobs = new ArrayList<>(List.of(
new Job("rental pricing", 180, 7, true),
new Job("selling parts", 260, 4, false),
new Job("repair bookings", 310, 5, true),
new Job("receipts", 140, 3, false),
new Job("text messages", 90, 2, false),
new Job("reorder list", 160, 3, true)));
jobs.sort(Comparator.comparingInt(Job::priority).reversed().thenComparing(Job::name));
int rank = 1;
for (Job j : jobs) System.out.printf("%d. %-16s priority %3d (%d lines, %d changes)%n", rank++, j.name(), j.priority(), j.linesTouched(), j.changesLastYear());
int total = jobs.stream().mapToInt(Job::linesTouched).sum();
System.out.println("lines accounted for: " + total + " of 1140");
}
}1. rental pricing priority 104 (180 lines, 7 changes) 2. repair bookings priority 90 (310 lines, 5 changes) 3. reorder list priority 63 (160 lines, 3 changes) 4. selling parts priority 53 (260 lines, 4 changes) 5. receipts priority 37 (140 lines, 3 changes) 6. text messages priority 24 (90 lines, 2 changes) lines accounted for: 1140 of 1140
What this code does
Each job CounterApp does is recorded with the lines it touches, how often Odile asked for changes to it last year and whether more changes are already waiting. The priority score weights frequent change most heavily, and the sort puts rental pricing first and repair bookings second, so those are where the redesign starts. The last line confirms that the six jobs account for all 1,140 lines of the class.
The ranking matches everyone's experience: rental pricing has changed seven times in a year and still has four copies. It becomes the first slice of the redesign, then repair bookings. The reorder list ranks third, but selling parts goes ahead of it, because the sell use case creates the PartCatalog port that the reorder list will need anyway. Receipts, text messages and the reorder list follow if time allows; if not, they stay in the legacy class behind the router until May.
| Evening | Date | Work |
|---|---|---|
| 1 | Tue Apr 18 | Characterization tests for rental pricing; router in front of CounterApp |
| 2 | Wed Apr 19 | Domain model: Money, RentalPeriod, BikeKind, Discount; one RentalPricing |
| 3 | Thu Apr 20 | QuoteRental use case and port; route quotes to the new code |
| 4 | Fri Apr 21 | Characterization tests for repair bookings; sealed RepairState |
| 5 | Mon Apr 24 | BookRepair use case; BookingStore port; spreadsheet and in-memory adapters |
| 6 | Tue Apr 25 | SellPart use case; PartCatalog port; contract tests for both adapters |
| 7 | Wed Apr 26 | Composition root; counter screen as a driving adapter |
| 8 | Fri Apr 28 | Diagrams, measurements and the review notes |
Step 2: one rule instead of four
The four copies of the rental price in CounterApp had drifted apart, as lesson 1 found. Before replacing them, Hamza runs all four against the same inputs, the characterization approach from lesson 10. Where they disagree, Odile decides which answer is right, and that decision becomes a test for the single new rule.
import java.util.*;
public class Main {
static int perDay(String bike) { return switch (bike) { case "CITY" -> 2500; case "CARGO" -> 4000; default -> 4500; }; }
// four legacy copies found in CounterApp, unchanged
static int quoteScreen(String bike, int days, boolean grad) { int c = perDay(bike) * (days == 7 ? 5 : days); return grad ? c - c / 10 : c; }
static int receiptCopy(String bike, int days, boolean grad) { int c = perDay(bike) * (days >= 7 ? 5 : days); return grad ? c - c / 10 : c; }
static int bookingCopy(String bike, int days, boolean grad) { int c = perDay(bike) * (days == 7 ? 5 : days); return c; }
static int reportCopy(String bike, int days, boolean grad) { int c = perDay(bike) * days; return grad ? c * 9 / 10 : c; }
public static void main(String[] args) {
Object[][] cases = { {"CITY", 3, false}, {"CITY", 7, false}, {"CARGO", 7, true}, {"TANDEM", 9, false}, {"CITY", 3, true} };
for (Object[] c : cases) {
String b = (String) c[0]; int d = (Integer) c[1]; boolean g = (Boolean) c[2];
int[] q = { quoteScreen(b, d, g), receiptCopy(b, d, g), bookingCopy(b, d, g), reportCopy(b, d, g) };
boolean agree = Arrays.stream(q).allMatch(x -> x == q[0]);
System.out.printf("%-6s %d days grad=%-5b %s%s%n", b, d, g, Arrays.toString(q), agree ? "" : " <- disagree");
}
}
}CITY 3 days grad=false [7500, 7500, 7500, 7500] CITY 7 days grad=false [12500, 12500, 12500, 17500] <- disagree CARGO 7 days grad=true [18000, 18000, 20000, 25200] <- disagree TANDEM 9 days grad=false [40500, 22500, 40500, 40500] <- disagree CITY 3 days grad=true [6750, 6750, 7500, 6750] <- disagree
What this code does
The four legacy versions of the rental price are copied out of CounterApp and run side by side on the same five cases. Only a three-day city rental without a discount gets the same answer from all four; the others show the drift, such as the receipt copy treating nine days as five and the booking copy forgetting the graduate discount. Each disagreeing line is a question for Odile, and her answers become the tests for the one new pricing rule.
Odile's answers take five minutes. The seven-day deal applies to exactly seven days, so a nine-day rental is charged nine days; the graduate discount applies everywhere. That makes the quote screen's version correct, and it becomes the single RentalPricing in the domain, with the other three call sites routed to it one at a time.
Step 3: the new shape
By the end of the sixth evening, the new code follows the hexagon of lesson 8. The domain package holds records for values, entities with ids, the sealed repair state and the aggregate for rental bookings, all from lesson 9. The application package holds one class per use case, each implementing a driving port, and the driven ports those use cases need. The adapters package holds the spreadsheet catalog, the booking file, the text-message sender and the counter screen. One class, the composition root, creates all the objects and wires them together, which is the only place that knows which adapter goes with which port.
The next example is a shrunken version of the whole new design in one file, with in-memory adapters, so that it can run here. It wires the parts together in a composition root and runs a short scripted Saturday morning through the driving port, exactly as the counter screen will.
import java.time.*;
import java.util.*;
public class Main {
// ---- domain ----
record Money(long cents) {
Money { if (cents < 0) throw new IllegalArgumentException("negative money"); }
Money times(int n) { return new Money(cents * n); }
Money lessTenth() { return new Money(cents - cents / 10); }
public String toString() { return String.format("%d.%02d", cents / 100, cents % 100); }
}
enum BikeKind { CITY(2500), CARGO(4000), TANDEM(4500); final long perDay; BikeKind(long p) { perDay = p; } }
static final class RentalPricing {
static Money quote(BikeKind kind, int days, boolean graduate) {
Money m = new Money(kind.perDay).times(days == 7 ? 5 : days);
return graduate ? m.lessTenth() : m;
}
}
record Part(String code, int onHand, int minimum) {
Part take(int n) { if (n > onHand) throw new IllegalArgumentException("only " + onHand + " " + code); return new Part(code, onHand - n, minimum); }
boolean low() { return onHand < minimum; }
}
// ---- application: driving port, driven ports, use cases ----
interface Counter { String quote(String kind, int days, boolean graduate); String sell(String code, int qty); }
interface PartCatalog { Part find(String code); void save(Part p); }
interface Notifier { void tell(String text); }
static final class CounterService implements Counter {
private final PartCatalog catalog; private final Notifier notifier; private final Clock clock;
CounterService(PartCatalog c, Notifier n, Clock k) { catalog = c; notifier = n; clock = k; }
public String quote(String kind, int days, boolean graduate) {
return kind + " for " + days + " days: " + RentalPricing.quote(BikeKind.valueOf(kind), days, graduate);
}
public String sell(String code, int qty) {
Part after = catalog.find(code).take(qty);
catalog.save(after);
if (after.low()) notifier.tell(code + " low at " + LocalTime.now(clock));
return qty + " " + code + " sold";
}
}
// ---- adapters ----
static final class MemoryCatalog implements PartCatalog {
private final Map<String, Part> m = new TreeMap<>();
public Part find(String code) { return m.get(code); }
public void save(Part p) { m.put(p.code(), p); }
}
// ---- composition root ----
static Counter wire(List<String> outbox) {
MemoryCatalog catalog = new MemoryCatalog();
catalog.save(new Part("TUBE-700x25", 11, 10));
catalog.save(new Part("BELL", 6, 2));
Clock saturday = Clock.fixed(Instant.parse("2028-05-06T14:05:00Z"), ZoneId.of("America/Toronto"));
return new CounterService(catalog, outbox::add, saturday);
}
public static void main(String[] args) {
List<String> outbox = new ArrayList<>();
Counter counter = wire(outbox);
System.out.println(counter.quote("CITY", 7, false));
System.out.println(counter.quote("CARGO", 2, true));
System.out.println(counter.sell("BELL", 1));
System.out.println(counter.sell("TUBE-700x25", 2));
try { counter.sell("BELL", 9); } catch (IllegalArgumentException e) { System.out.println("refused: " + e.getMessage()); }
System.out.println("messages for Kofi: " + outbox);
}
}CITY for 7 days: 125.00 CARGO for 2 days: 72.00 1 BELL sold 2 TUBE-700x25 sold refused: only 5 BELL messages for Kofi: [TUBE-700x25 low at 10:05]
What this code does
The domain records hold the rules, the single CounterService implements the driving port using only driven ports and a clock, and the wire method is the composition root that picks in-memory adapters and a fixed Saturday clock. The scripted morning quotes two rentals, sells a bell and two tubes, and has a sale of nine bells refused. Only the tube sale takes a part below its minimum, so it is the only message waiting for Kofi.
In the real program, wire is a class of its own in the adapters package, and it chooses the spreadsheet catalog, the booking file, the real text-message sender and the system clock. The tests use a second composition root with in-memory adapters and a fixed clock. Nothing else changes between the two, which is the whole point.
Step 4: protect the shape
A good design decays if nothing defends it. One hurried evening someone imports the spreadsheet adapter into a use case, and the hexagon has a hole in it. Lesson 7 checked layer rules with a small program; in the real build, Leif adds the same check as a test that runs on every pull request, using the ArchUnit library, which reads compiled classes and fails the build when a forbidden dependency appears. The rule is a direct statement of the dependency rule: nothing in domain or application may depend on adapters.
import java.util.*;
public class Main {
record Dependency(String fromClass, String toClass) {
String fromPackage() { return fromClass.substring(0, fromClass.lastIndexOf('.')); }
String toPackage() { return toClass.substring(0, toClass.lastIndexOf('.')); }
}
static final Map<String, Set<String>> ALLOWED = Map.of(
"counter.domain", Set.of("counter.domain"),
"counter.application", Set.of("counter.application", "counter.domain"),
"counter.adapters", Set.of("counter.adapters", "counter.application", "counter.domain"));
static List<String> violations(List<Dependency> deps) {
List<String> out = new ArrayList<>();
for (Dependency d : deps)
if (!ALLOWED.get(d.fromPackage()).contains(d.toPackage())) out.add(d.fromClass() + " -> " + d.toClass());
return out;
}
public static void main(String[] args) {
List<Dependency> clean = List.of(
new Dependency("counter.application.SellPartService", "counter.domain.Part"),
new Dependency("counter.application.SellPartService", "counter.application.PartCatalog"),
new Dependency("counter.adapters.SpreadsheetCatalog", "counter.application.PartCatalog"),
new Dependency("counter.adapters.Wiring", "counter.application.SellPartService"));
System.out.println("pull request 81: " + (violations(clean).isEmpty() ? "dependency rule holds" : violations(clean)));
List<Dependency> hurried = new ArrayList<>(clean);
hurried.add(new Dependency("counter.application.BookRepairService", "counter.adapters.BookingFile"));
hurried.add(new Dependency("counter.domain.Repair", "counter.adapters.TextMessages"));
System.out.println("pull request 82: build fails");
violations(hurried).forEach(v -> System.out.println(" forbidden: " + v));
}
}pull request 81: dependency rule holds pull request 82: build fails forbidden: counter.application.BookRepairService -> counter.adapters.BookingFile forbidden: counter.domain.Repair -> counter.adapters.TextMessages
What this code does
The ALLOWED map states which packages each package may depend on, which is the hexagon's rule that dependencies point inward. A clean set of dependencies passes, while a hurried change that makes a use case and a domain class reach into adapters produces two named violations. In the real build this check runs in continuous integration, so a pull request that breaks the rule cannot be merged.
Step 5: measure again
On the last evening Hamza repeats lesson 1's measurement. He takes the same six requests Odile made over the past year and asks, for each, how many places in the new design would have had to change. He then tries a seventh, the one that started the course: a discount for earn-a-bike graduates on repairs as well as rentals. In the old code that would have meant finding every price calculation again. In the new design it is one new Discount, written and tested in twenty minutes on April 28.
import java.util.*;
public class Main {
record Change(String request, int placesBefore, int placesAfter) {}
public static void main(String[] args) {
List<Change> changes = List.of(
new Change("graduate discount", 4, 1),
new Change("new tandem price", 4, 1),
new Change("tax on receipts only", 3, 1),
new Change("phone numbers hidden in logs", 6, 1),
new Change("new bell supplier", 2, 1),
new Change("Saturday repair hours", 3, 1),
new Change("graduate discount on repairs", 5, 1));
int before = 0, after = 0;
for (Change c : changes) {
before += c.placesBefore(); after += c.placesAfter();
System.out.printf("%-30s %d -> %d%n", c.request(), c.placesBefore(), c.placesAfter());
}
System.out.printf("average places per change: %.1f -> %.1f%n", before / (double) changes.size(), after / (double) changes.size());
}
}graduate discount 4 -> 1 new tandem price 4 -> 1 tax on receipts only 3 -> 1 phone numbers hidden in logs 6 -> 1 new bell supplier 2 -> 1 Saturday repair hours 3 -> 1 graduate discount on repairs 5 -> 1 average places per change: 3.9 -> 1.0
What this code does
Each record compares how many places a request touched in the old CounterApp with how many it would touch in the redesigned one. Every request now lands in exactly one place, such as one Discount class, one entry in BikeKind or one adapter, so the average drops from about 3.9 places per change to 1.0. These numbers, not the diagrams, are what Odile will care about at the review.
One place per change is the ideal, not a law. Some future changes will cut across the design, and Hamza says so in his notes rather than pretending otherwise. But the six requests that actually happened last year would each have been a small, local, tested change.
The review
The review on Tuesday, May 2 is planned as forty minutes. Ingrid's advice is to spend almost none of it on code. Hamza will show the before-and-after diagram, the sequence diagram for selling a part from lesson 11, the state diagram for repairs, which Odile is asked to check line by line, and the measurement table. Then each person in the room asks the question they care about, and the design must answer it.
| Reviewer | Their question | Where the design answers it |
|---|---|---|
| Odile | How long will my next price change take? | One Discount or one BikeKind entry; the measurement table |
| Kofi | What happens if the spreadsheet is renamed again? | Only the spreadsheet adapter changes; its contract test catches mistakes |
| Leif | How do we stop the design decaying? | The dependency-rule check in continuous integration |
| Ingrid | What did you decide not to do, and why? | The decision record: receipts and the reorder list stay in legacy until May |
| Tamsin | Will the repair screen still show my sign-off? | FINISHED carries signedOffBy; the state diagram shows it |
Ingrid's question deserves its own answer. A design is a set of decisions, and the reasons are lost quickly. Hamza keeps a short architecture decision record for each important choice, an idea Michael Nygard described in 2011: a page with the context, the decision and its consequences. The capstone has four: use ports and adapters; keep the spreadsheet for now behind a port rather than move to a database; strangle CounterApp feature by feature; and leave receipts and the reorder list in the legacy class until after the review.
After the review, if the design is accepted, the new CounterApp runs beside the old one for two Saturdays. Then the legacy class shrinks over May as receipts and the reorder list move across, and when the router sends it nothing, it is deleted. Later in 2028, the plan is for the shop's booking website, the kind of Spring Boot service Hamza is learning to build in his web services course this same term, to sit on top of the same driving ports, adding a web adapter without touching the core. That is the test of the design that matters most: the next feature nobody has thought of yet.
| Lesson | Where it shows up in the capstone |
|---|---|
| 1. What makes design good | Measuring change cost before and after |
| 2. SOLID | One reason to change per class; ports inverted toward the core |
| 3 to 5. Patterns | Factory for BikeKind, decorator for caching prices, strategy for discounts, state for repairs |
| 6. Composition over inheritance | Discounts composed, never subclassed |
| 7 and 8. Architecture | The hexagon and its dependency check |
| 9. Domain modelling | Records, entities, invariants and the rental aggregate |
| 10. Legacy code | Characterization tests and the strangler router |
| 11. UML | The diagrams at the review |
Try it yourself
Add a feature in one place
The redesigned pricing uses a list of Discount strategies. Add the new rule from the capstone, a graduate discount of one tenth that applies only when the customer is a graduate, by writing one new class GraduateDiscount implements Discount and adding it to the list. Do not change any other code.
The program should print CITY 3 days, graduate: 6750 and CITY 3 days, regular: 7500.
import java.util.*;
public class Main {
record Customer(boolean graduate) {}
interface Discount { long apply(long cents, Customer c); }
static final class WeekDeal implements Discount {
private final int days;
WeekDeal(int days) { this.days = days; }
public long apply(long cents, Customer c) { return days == 7 ? cents * 5 / 7 : cents; }
}
static long price(long perDay, int days, Customer c, List<Discount> discounts) {
long cents = perDay * days;
for (Discount d : discounts) cents = d.apply(cents, c);
return cents;
}
public static void main(String[] args) {
List<Discount> discounts = List.of(new WeekDeal(3));
System.out.println("CITY 3 days, graduate: " + price(2500, 3, new Customer(true), discounts));
System.out.println("CITY 3 days, regular: " + price(2500, 3, new Customer(false), discounts));
}
}Try it yourself
Wire a composition root
The starter's QuoteService creates its own price table inside, so tests cannot give it different prices. Change QuoteService to receive a PriceTable through its constructor, and write a method wire() that builds it with a TablePrices adapter holding CITY at 2500 and CARGO at 4000.
The program should print CARGO x2 = 8000.
import java.util.*;
public class Main {
interface PriceTable { long perDay(String kind); }
static final class QuoteService {
private final Map<String, Long> prices = Map.of("CITY", 2500L);
String quote(String kind, int days) { return kind + " x" + days + " = " + prices.getOrDefault(kind, 0L) * days; }
}
public static void main(String[] args) {
System.out.println(new QuoteService().quote("CARGO", 2));
}
}Common mistakes
MistakeStarting the redesign by rewriting everything at once.
InsteadStrangle the old program slice by slice, keeping it working every day.
MistakeChoosing the first slice by what is most interesting.
InsteadStart with the job that changes most often and is most tangled.
MistakeReplacing duplicated rules without comparing them.
InsteadRun all copies side by side and let the business decide the disagreements.
MistakeLetting any class create its own adapters.
InsteadWire everything in one composition root.
MistakePresenting a redesign as diagrams and code alone.
InsteadShow the cost of real changes before and after, and the decisions you made.
Summary and key terms
- The capstone redesigns CounterApp, a 1,140-line class with no tests, over eight evenings in April 2028, with a review on Tuesday, May 2.
- It begins by measuring which jobs change most and are most tangled, and starts with rental pricing.
- The four drifting copies of the price are compared with characterization tests, the owner settles the disagreements, and one rule replaces them.
- The new design is a hexagon: a domain model of records, entities, a sealed repair state and an aggregate; use cases behind driving ports; driven ports implemented by adapters; and one composition root that wires them.
- A dependency-rule check in continuous integration protects the shape.
- Measuring the same requests again shows each now landing in one place.
- The review answers each stakeholder's question and records the main choices as architecture decision records.
- The old class is strangled feature by feature, and a planned web adapter will reuse the same ports.
- Capstone
- A final project that brings together the course's ideas on a real problem.
- Slice
- One feature moved from the old code to the new design as a unit.
- Composition root
- The one place where all objects are created and wired to their adapters.
- Dependency rule
- The rule that code dependencies point inward toward the domain.
- ArchUnit
- A Java library for testing architecture rules such as allowed package dependencies.
- Architecture decision record
- A short note of the context, decision and consequences of one important design choice.
- Change cost
- The number of places and the risk involved in making a change.
- Strangler router
- The routing layer that sends each feature to the old or the new code.
- Contract test
- A test that every adapter for a port must pass.
- Design review
- A meeting in which a design is explained and questioned by the people it affects.
- Technical debt
- The extra cost of later changes caused by earlier shortcuts.
- Running in parallel
- Using the old and new systems side by side until the new one is trusted.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why does the redesign start with rental pricing?
Show answer
It changes most often, is tangled and has more changes waiting.
The four price copies disagree on a nine-day rental. Who decides which is right?
Show answer
The business, Odile, and her answer becomes a test.
Where are the spreadsheet adapter and the system clock chosen?
Show answer
Only in the composition root.
How is the dependency rule enforced after the capstone?
Show answer
An automated check runs on every pull request and fails the build on a violation.
What will the planned booking website add to the design?
Show answer
A new web driving adapter on the same ports, without changing the core.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.