JAVA-220 · Lesson 12 of 12 · 22 min
Capstone: testing and refactoring a legacy module
▶ Video coming soon A video version of this lesson is on the way.
The capstone ran from Monday, December 6 to Friday, December 10, 2027, with the review on Thursday, December 16. The job was the one Ingrid had promised in September: take a part of PartsDesk that has no tests, put tests around it, improve its design without changing what it does, and only then add a feature. The part was Hamza's own low-stock report from November 2026, still running every morning on the back-office computer, still built from parallel arrays and string concatenation. "Your code from a year ago is legacy code now," Ingrid said. "That is normal. What matters is whether you can change it safely." The feature was Kofi's: the supplier sells tubes in boxes of 10, chains in packs of 5 and cables in bundles of 10, and the suggested orders should be rounded up to whole packs.
The requirements
Hamza started by writing down what the finished work had to do, with Kofi, in words both of them could check. Each requirement names the test that will prove it, so the review can check the requirements one by one.
| Req. | Requirement | Proved by |
|---|---|---|
| R1 | The low report's existing output does not change unless packs are switched on | Characterization test on Kofi's six parts |
| R2 | A part is low when its count is at or below its reorder level | Boundary tests: count equal to level, and one above |
| R3 | With packs on, each order is rounded up to a whole number of packs | Parameterized tests of roundUpToPack |
| R4 | A pack size below 1 is rejected with a clear message | assertThrows test |
| R5 | The weekly e-mail is sent once when something is low and not at all otherwise | Mock notifier tests |
| R6 | Every change reaches main through a reviewed pull request with a green build | The pull request and its CI run |
Step 1: characterize
The legacy report had no tests, so the first step changed nothing. Hamza ran the old code on Kofi's six real starting parts from PartsDesk 1.0 and captured the output exactly, then turned it into the expected value of a characterization test.
public class Main {
// PartsDesk 1.0 (November 2026): the low-stock report, as written.
static String[] bin = {"A-02", "A-03", "B-11", "C-14", "D-07", "D-08"};
static String[] name = {"700x25c tube", "26in tube", "Brake pads", "Chain 8-speed", "Brake cable", "Gear cable"};
static int[] count = {15, 22, 32, 6, 41, 9};
static int[] level = {40, 20, 15, 10, 25, 25};
static String lowReport() {
String s = "";
int n = 0;
for (int i = 0; i < bin.length; i++) {
if (count[i] <= level[i]) {
s = s + bin[i] + " " + name[i] + " " + count[i] + "/" + level[i] + " order " + (level[i] * 2 - count[i]) + "\n";
n++;
}
}
if (n == 0) s = "Nothing is low.\n";
else s = s + n + " part(s) low\n";
return s;
}
public static void main(String[] args) {
System.out.print(lowReport());
}
}A-02 700x25c tube 15/40 order 65 C-14 Chain 8-speed 6/10 order 14 D-08 Gear cable 9/25 order 41 3 part(s) low
What this code does
The legacy report loops over four parallel arrays, one per field, and appends a line for each part at or below its level, with the suggested order of twice the level minus the count. Kofi's six parts give three low lines, for the tubes, the chains and the gear cables, and a count at the end. This output, captured as it is, becomes the expected value for everything that follows.
Hamza also added two characterization cases the real data did not cover: a part exactly on its level, which the report lists, and a list with nothing low, which prints "Nothing is low.". Both behaviors were confirmed by Kofi as intended, so they also became requirement R2's tests.
Step 2: refactor under the tests
With the characterization test in place, Hamza refactored in small steps, running it after each one and committing at each green run. The parallel arrays became a list of Part records, which also gained the new packSize field, unused for now. The string concatenation became a StringBuilder. The report method stopped reading global arrays and took the list of parts as a parameter, which made it testable with any data. Nine commits later, the code looked new and the characterization test still passed.
import java.util.*;
public class Main {
record Part(String bin, String name, int count, int level, int packSize) {
boolean isLow() { return count <= level; }
int suggestedOrder() { return level * 2 - count; }
}
static int roundUpToPack(int quantity, int packSize) {
if (packSize < 1) throw new IllegalArgumentException("pack size must be at least 1: " + packSize);
return (quantity + packSize - 1) / packSize * packSize;
}
static String lowReport(List<Part> parts, boolean usePacks) {
StringBuilder sb = new StringBuilder();
int n = 0;
for (Part p : parts) {
if (!p.isLow()) continue;
int order = usePacks ? roundUpToPack(p.suggestedOrder(), p.packSize()) : p.suggestedOrder();
sb.append(p.bin()).append(' ').append(p.name()).append(' ').append(p.count()).append('/').append(p.level())
.append(" order ").append(order).append('\n');
n++;
}
return n == 0 ? "Nothing is low.\n" : sb.append(n).append(" part(s) low\n").toString();
}
static final List<Part> KOFI = List.of(
new Part("A-02", "700x25c tube", 15, 40, 10), new Part("A-03", "26in tube", 22, 20, 10),
new Part("B-11", "Brake pads", 32, 15, 4), new Part("C-14", "Chain 8-speed", 6, 10, 5),
new Part("D-07", "Brake cable", 41, 25, 10), new Part("D-08", "Gear cable", 9, 25, 10));
static final String EXPECTED = """
A-02 700x25c tube 15/40 order 65
C-14 Chain 8-speed 6/10 order 14
D-08 Gear cable 9/25 order 41
3 part(s) low
""";
public static void main(String[] args) {
String actual = lowReport(KOFI, false);
System.out.print(actual);
System.out.println(actual.equals(EXPECTED) ? "PASS characterization: output unchanged" : "FAIL characterization: output changed");
}
}A-02 700x25c tube 15/40 order 65 C-14 Chain 8-speed 6/10 order 14 D-08 Gear cable 9/25 order 41 3 part(s) low PASS characterization: output unchanged
What this code does
Part is now a record with a pack size, and lowReport takes the list of parts and a switch for the new feature, which stays off here. The expected text in the test is the exact output captured from the legacy code in step 1. With packs switched off, the refactored report produces it character for character, which proves requirement R1 for this data.
Step 3: test-drive the feature
Only now did Hamza change behavior, test-first. He wrote the rounding rule as a table of cases with Kofi, watched the tests fail against a stub that returned the quantity unchanged, and then wrote roundUpToPack. The table includes the edges: a quantity already a whole number of packs, a pack of 1, and a quantity of 0.
public class Main {
static int roundUpToPack(int quantity, int packSize) {
if (packSize < 1) throw new IllegalArgumentException("pack size must be at least 1: " + packSize);
return (quantity + packSize - 1) / packSize * packSize;
}
public static void main(String[] args) {
int[][] cases = {
// quantity, pack size, expected
{65, 10, 70}, {14, 5, 15}, {41, 10, 50}, {40, 10, 40}, {7, 1, 7}, {0, 10, 0}, {1, 4, 4},
};
int failed = 0;
for (int[] c : cases) {
int actual = roundUpToPack(c[0], c[1]);
boolean ok = actual == c[2];
if (!ok) failed++;
System.out.printf(" %2d in packs of %2d -> %2d %s%n", c[0], c[1], actual, ok ? "ok" : "FAIL, expected " + c[2]);
}
try {
roundUpToPack(5, 0);
failed++;
System.out.println(" FAIL pack size 0 was accepted");
} catch (IllegalArgumentException e) {
System.out.println(" rejected: " + e.getMessage());
}
System.out.println(failed == 0 ? "All rounding tests pass" : failed + " failed");
}
}65 in packs of 10 -> 70 ok 14 in packs of 5 -> 15 ok 41 in packs of 10 -> 50 ok 40 in packs of 10 -> 40 ok 7 in packs of 1 -> 7 ok 0 in packs of 10 -> 0 ok 1 in packs of 4 -> 4 ok rejected: pack size must be at least 1: 0 All rounding tests pass
What this code does
The table of quantities and pack sizes is the parameterized test for requirement R3, and every row passes, including 40 in packs of 10, which must stay 40. Adding one less than the pack size before dividing makes integer division round up instead of down, a common idiom worth testing at its edges. The last check proves requirement R4: a pack size of zero is rejected with a message, rather than causing a division by zero.
In the real build these became a JUnit @ParameterizedTest with a @CsvSource holding the same rows, and an assertThrows test, in partsdesk/src/test/java. The plain Java versions here produce the same checks without the libraries.
@ParameterizedTest(name = "{0} in packs of {1} rounds up to {2}")
@CsvSource({"65, 10, 70", "14, 5, 15", "41, 10, 50", "40, 10, 40", "7, 1, 7", "0, 10, 0", "1, 4, 4"})
void roundsUpToWholePacks(int quantity, int packSize, int expected) {
assertEquals(expected, Reorder.roundUpToPack(quantity, packSize));
}
@Test
void rejectsPackSizeBelowOne() {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> Reorder.roundUpToPack(5, 0));
assertEquals("pack size must be at least 1: 0", e.getMessage());
}What this code does
The CSV rows are the same seven cases as the plain Java table, and the name pattern makes each run read as a sentence in the report. The second test checks both the exception type and its message, so a later change that throws a vaguer exception would be caught. Together they cover requirements R3 and R4 in partsdesk's test suite.
Step 4: the finished report
With the rounding rule tested, switching the feature on was one argument. Hamza ran the full report both ways for Kofi, and checked the weekly e-mail logic from lesson 5 with a recording notifier, for requirement R5.
import java.util.*;
public class Main {
record Part(String bin, String name, int count, int level, int packSize) {
boolean isLow() { return count <= level; }
int suggestedOrder() { return level * 2 - count; }
}
static int roundUpToPack(int quantity, int packSize) {
if (packSize < 1) throw new IllegalArgumentException("pack size must be at least 1: " + packSize);
return (quantity + packSize - 1) / packSize * packSize;
}
static String lowReport(List<Part> parts, boolean usePacks) {
StringBuilder sb = new StringBuilder();
int n = 0;
for (Part p : parts) {
if (!p.isLow()) continue;
int order = usePacks ? roundUpToPack(p.suggestedOrder(), p.packSize()) : p.suggestedOrder();
sb.append(p.bin()).append(' ').append(p.name()).append(' ').append(p.count()).append('/').append(p.level())
.append(" order ").append(order).append('\n');
n++;
}
return n == 0 ? "Nothing is low.\n" : sb.append(n).append(" part(s) low\n").toString();
}
static final List<Part> KOFI = List.of(
new Part("A-02", "700x25c tube", 15, 40, 10), new Part("A-03", "26in tube", 22, 20, 10),
new Part("B-11", "Brake pads", 32, 15, 4), new Part("C-14", "Chain 8-speed", 6, 10, 5),
new Part("D-07", "Brake cable", 41, 25, 10), new Part("D-08", "Gear cable", 9, 25, 10));
interface Notifier { void send(String to, String subject, String body); }
static class RecordingNotifier implements Notifier {
final List<String> bodies = new ArrayList<>();
public void send(String to, String subject, String body) { bodies.add(to + " | " + subject); }
}
static void weekly(List<Part> parts, Notifier n) {
String report = lowReport(parts, true);
if (!report.equals("Nothing is low.\n")) n.send("kofi@secondgear.example", "Weekly reorder", report);
}
public static void main(String[] args) {
System.out.println("Orders in whole packs:");
System.out.print(lowReport(KOFI, true));
RecordingNotifier mock = new RecordingNotifier();
weekly(KOFI, mock);
System.out.println("E-mails when parts are low: " + mock.bodies.size() + " (" + mock.bodies.get(0) + ")");
RecordingNotifier quiet = new RecordingNotifier();
weekly(List.of(new Part("BELL", "Bell", 9, 4, 6)), quiet);
System.out.println("E-mails when nothing is low: " + quiet.bodies.size());
}
}Orders in whole packs: A-02 700x25c tube 15/40 order 70 C-14 Chain 8-speed 6/10 order 15 D-08 Gear cable 9/25 order 50 3 part(s) low E-mails when parts are low: 1 (kofi@secondgear.example | Weekly reorder) E-mails when nothing is low: 0
What this code does
With packs switched on, the tubes' order of 65 becomes 70, the chains' 14 becomes 15 and the gear cables' 41 becomes 50, matching the rows Kofi agreed in the rounding table. The recording notifier shows one e-mail to Kofi when parts are low and none for a list where nothing is low, which proves requirement R5 without sending any mail. Every number here was already checked by a smaller test, so this run is a final end-to-end confirmation rather than the only evidence.
Step 5: coverage, review and CI
Before opening the pull request, Hamza looked at the JaCoCo report for the new Reorder class. Branch coverage was complete except for one branch: the "Nothing is low." line when packs are switched on. He added a test for it, not to raise the number but because the report pointed at a behavior nobody had checked. He then ran the mutation idea from lesson 8 by hand on roundUpToPack, deleting the - 1, and was pleased to see the 40-in-packs-of-10 row fail at once: without it, a quantity that is already a whole number of packs gets one pack too many.
PR 57: Round reorder quantities up to supplier pack sizesWhat: Low report now built from Part records; new roundUpToPack; packs switched on in the weekly e-mail.
Why: Kofi orders tubes in boxes of 10, chains in packs of 5, cables in bundles of 10 (R3).
Tests: characterization (R1), boundaries (R2), 7 pack cases + bad pack size (R3, R4),
recording-notifier tests (R5). Coverage of Reorder: all branches.
Commits: 14 (9 refactoring steps, each green; then the feature test-first)
✓ build / build (pull_request) Successful in 1m 51s
Ingrid Vallancourt commented on Reorder.java line 18:
What happens if Kofi types a pack size of 0 in the parts file? It throws, which is right,
but the morning report would then fail for every part. Catch it per part and log a WARN?
Ingrid Vallancourt commented on Part.java line 3:
suggestion: packSize could default to 1 when the file has no column for it.
Leif Quarmby approved these changesWhat this code does
The pull request description lists what changed and why, how it was tested and which requirements each test covers, so the reviewers could check the work against the plan. CI ran the whole build, including the coverage floor, and passed. Ingrid's review left two comments, one a real problem and one a suggestion, and Leif approved after both were answered.
Ingrid's first comment was a real bug that no test had caught, because no test had asked what one bad row in Kofi's file would do to the whole report. Hamza wrote that test first, watched it fail, then made the report skip and log a bad row with a WARN, as lesson 9 taught. The second comment became a default value with its own test. The pull request was merged on Friday, December 10, with 19 tests for the report where a year earlier there had been none.
The review
At the review on Thursday, December 16, Kofi ran the new report on the full parts list of 612 kinds and compared a dozen orders with his own arithmetic; all matched. Odile asked how she would know if a future change broke the prices or the reorders. Hamza showed her the pull request page: every change now arrives with tests, a green build and a second reader. Leif's verdict was short: "This is how professional teams work. Not because the code is perfect, but because they can change it on a Tuesday without being afraid."
| Requirement | Result at the review |
|---|---|
| R1 output unchanged with packs off | Pass: characterization test, plus two extra cases |
| R2 at or below the level | Pass: boundary tests at the level and one above |
| R3 round up to whole packs | Pass: seven parameterized cases agreed with Kofi |
| R4 reject bad pack sizes | Pass, and extended after review: one bad row is skipped and logged, not fatal |
| R5 e-mail once, or not at all | Pass: recording-notifier tests |
| R6 reviewed pull request, green build | Pass: PR 57, approved by Leif after two comments from Ingrid |
Kofi's trial of pack-size orders begins with the first supplier order of the new year, planned for Monday, January 10, 2028. Hamza's list of future work for next term had three items: move the parts list from a file into a database, with integration tests from lesson 7; put the reorder rules behind a small web service; and, Odile's request, a test for the youth discount rule that was finally decided in November.
Try it yourself
Round up to whole packs
Complete roundUpToPack so it rounds a quantity up to the next whole number of packs, returns the quantity unchanged when it is already a whole number of packs, and throws an IllegalArgumentException for a pack size below 1. Use integer arithmetic only.
The program should print 70 15 40 0 4 and then rejected.
public class Main {
static int roundUpToPack(int quantity, int packSize) {
return quantity;
}
public static void main(String[] args) {
System.out.println(roundUpToPack(65, 10) + " " + roundUpToPack(14, 5) + " " + roundUpToPack(40, 10) + " "
+ roundUpToPack(0, 10) + " " + roundUpToPack(1, 4));
try {
roundUpToPack(5, 0);
System.out.println("accepted");
} catch (IllegalArgumentException e) {
System.out.println("rejected");
}
}
}Try it yourself
One bad row must not stop the report
Ingrid's review comment: a part with a pack size of 0 makes orders throw, so no orders are produced at all. Change orders so that a part whose rounding throws is skipped, with a line skipped X: followed by the exception's message (where X is the bin), while the other parts are still listed.
The program should print A-02 70, skipped C-14: pack size must be at least 1: 0 and D-08 50.
import java.util.*;
public class Main {
record Part(String bin, int count, int level, int packSize) {
int suggestedOrder() { return level * 2 - count; }
}
static int roundUpToPack(int quantity, int packSize) {
if (packSize < 1) throw new IllegalArgumentException("pack size must be at least 1: " + packSize);
return (quantity + packSize - 1) / packSize * packSize;
}
static List<String> orders(List<Part> parts) {
List<String> lines = new ArrayList<>();
for (Part p : parts) {
lines.add(p.bin() + " " + roundUpToPack(p.suggestedOrder(), p.packSize()));
}
return lines;
}
public static void main(String[] args) {
List<Part> parts = List.of(new Part("A-02", 15, 40, 10), new Part("C-14", 6, 10, 0), new Part("D-08", 9, 25, 10));
try {
orders(parts).forEach(System.out::println);
} catch (IllegalArgumentException e) {
System.out.println("report failed: " + e.getMessage());
}
}
}Common mistakes
MistakeChanging legacy code's behavior and structure in the same step.
InsteadCharacterize first, refactor with the behavior fixed, then add features test-first.
MistakeAdding a feature to untested code because it is small.
InsteadPut a characterization test around the code before touching it, however small the change.
MistakeReading the coverage report as a score.
InsteadUse it to find untested behavior, then write a real test for that behavior.
MistakeTreating review comments as criticism to defend against.
InsteadTreat them as free testing: write the missing test, then fix the code.
MistakeLetting one bad input row stop a whole report.
InsteadHandle and log the bad row, keep going, and test that behavior.
Summary and key terms
- The capstone applied the whole course to Hamza's own untested low-stock report from 2026.
- Requirements were written first, each with the test that proves it.
- A characterization test captured the legacy output on Kofi's real parts.
- Refactoring in small, committed steps replaced parallel arrays with Part records and a testable method taking its data as a parameter, while the characterization test stayed green.
- The pack-size feature was then test-driven from a table of cases agreed with Kofi, including edges and a rejected pack size, and the weekly e-mail was checked with a recording notifier.
- Coverage pointed at one untested branch, a hand mutation confirmed the rounding tests were strong, and the work reached main through a reviewed pull request with a green build.
- The review found a real bug, one bad row stopping the report, which was fixed test-first.
- Capstone
- The final project of a course, bringing together its skills.
- Requirement
- A statement of what the software must do, written so it can be checked.
- Characterization test
- A test recording what existing code does now, used to guard changes.
- Pack size
- The number of items a supplier sells in one unit, such as a box of 10 tubes.
- Round up
- To move a number up to the next whole multiple, such as 65 to 70 in packs of 10.
- Pull request description
- The text explaining what a change does, why, and how it was tested.
- Review finding
- A problem or improvement a reviewer identifies in a pull request.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why did Hamza characterize the old report before changing anything?
Show answer
So every refactoring step could be checked against the code's real current behavior.
Why was packSize added to Part during refactoring but not used?
Show answer
To prepare the structure, while keeping behavior unchanged until the feature was test-driven.
What does adding packSize - 1 before dividing do?
Show answer
It makes integer division round up instead of down.
What bug did Ingrid's review find?
Show answer
One part with a pack size of 0 stopped the whole report.
Which requirement does the recording notifier test prove?
Show answer
R5: the e-mail is sent once when something is low and not at all otherwise.
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.