JAVA-270 · Lesson 10 of 12 · 25 min

Working with legacy code

▶ Video coming soon A video version of this lesson is on the way.

Tuesday, March 21, 2028. Everything so far this term has been about how code should be shaped. Tonight is about the code Second Gear actually has. CounterApp.java, the program on the counter computer, is only eight months old, but Hamza built it in a hurry in the summer of 2027 by pasting together PartsDesk, ShopBook and the RentalDesk prices. The JUnit tests he wrote in his testing course stayed behind with the originals; the pasted copies have none. In October he also copied the pack-size rounding from PR 57 into CounterApp by hand, again without its tests. The class is 1,140 lines long, it reads the spreadsheet directly from button handlers, and nothing in it is checked automatically. The capstone in four weeks is to redesign it. Tonight's lesson is how to change such code without breaking the shop.

What legacy code is

Michael Feathers's book Working Effectively with Legacy Code (2004) begins with a blunt definition: legacy code is simply code without tests. Age has nothing to do with it; a class written last week, or last summer, with no tests is legacy code by this definition, and a twenty-year-old library with a thorough suite is not. The reason the definition is useful is that it names the actual problem. Without tests, you cannot tell whether a change preserved what the code did, so every change is a gamble, and people stop improving the code because they are afraid of it.

Feathers calls the situation the legacy code dilemma: to change code safely you need tests, but to put tests in place you often need to change the code, because it was not written to be tested. CounterApp calls the system clock, opens the spreadsheet file and shows dialog boxes, all inside one method. You cannot test that method without a screen and a file. The way out is a small number of very careful, mechanical changes that break just enough dependencies to get tests in, then the real refactoring under the protection of those tests.

The legacy code change algorithm
StepWhat Feathers recommendsAt Second Gear
1. Identify change pointsFind where the change must goThe reorder calculation inside CounterApp
2. Find test pointsFind where behavior can be observedThe quantity the method returns
3. Break dependenciesMake the minimum change to get the code into a testPass the clock and catalog in
4. Write testsCharacterization tests that pin down current behaviorRecord today's reorder quantities
5. Change and refactorMake the change, then clean up under testMove the rule into the domain

Characterization tests

A normal test says what the code should do. A characterization test says what the code actually does now, right or wrong. You write it by calling the code with some input, looking at what comes out, and writing an assertion that it keeps coming out. The point is not to judge the behavior but to notice when it changes. If you later find that some current behavior is a bug, you fix it deliberately and update the test, rather than changing it by accident.

Here is the reorder rule as it lives inside CounterApp today, pulled out just far enough to call. Nobody remembers all its special cases. The characterization test feeds it a range of inputs and records what it gives back.

Java Example · Main.java
import java.util.*;

public class Main {
    // copied unchanged from CounterApp.reorderClicked, 2027
    static int legacyReorder(int onHand, int minimum, int packSize, boolean clearance) {
        if (clearance) return 0;
        int need = minimum * 2 - onHand;
        if (need <= 0) return 0;
        if (packSize > 1) {
            int packs = need / packSize;
            if (need % packSize != 0) packs++;
            return packs * packSize;
        }
        if (need > 50) need = 50;
        return need;
    }

    public static void main(String[] args) {
        int[][] cases = { {3, 10, 1, 0}, {3, 10, 6, 0}, {12, 10, 6, 0}, {25, 10, 6, 0}, {0, 40, 1, 0}, {0, 40, 25, 0}, {2, 10, 1, 1} };
        for (int[] c : cases) {
            int q = legacyReorder(c[0], c[1], c[2], c[3] == 1);
            System.out.printf("onHand=%2d min=%2d pack=%2d clearance=%-5b -> %d%n", c[0], c[1], c[2], c[3] == 1, q);
        }
    }
}
Output
onHand= 3 min=10 pack= 1 clearance=false -> 17
onHand= 3 min=10 pack= 6 clearance=false -> 18
onHand=12 min=10 pack= 6 clearance=false -> 12
onHand=25 min=10 pack= 6 clearance=false -> 0
onHand= 0 min=40 pack= 1 clearance=false -> 50
onHand= 0 min=40 pack=25 clearance=false -> 100
onHand= 2 min=10 pack= 1 clearance=true  -> 0

What this code does

The method is copied unchanged from the old CounterApp class and run over a spread of inputs, and each line of output records what it does today. Two surprises show up straight away: the cap of 50 applies only to parts sold singly, so 0 on hand with a minimum of 40 gives 50 for singles but 100 when packed in 25s, and clearance parts are never reordered. Those lines become the expected values of characterization tests before anyone touches the code.

The cap of 50 surprised Kofi. He thought it applied to everything. Was it a bug? Odile thinks it was deliberate for singles and simply lost when Hamza copied the pack sizes from PR 57 into CounterApp, but she wants to decide later. For now the characterization test pins it down, and a note goes in the list of questions for the capstone. This is the discipline: first preserve, then decide.

Turning those observations into checks is mechanical. Each case becomes an assertion with the observed value as the expected value.

Java Example · Main.java
public class Main {
    static int legacyReorder(int onHand, int minimum, int packSize, boolean clearance) {
        if (clearance) return 0;
        int need = minimum * 2 - onHand;
        if (need <= 0) return 0;
        if (packSize > 1) {
            int packs = need / packSize;
            if (need % packSize != 0) packs++;
            return packs * packSize;
        }
        if (need > 50) need = 50;
        return need;
    }

    static int failures = 0;
    static void pin(String name, int actual, int recorded) {
        if (actual != recorded) { failures++; System.out.println("CHANGED " + name + ": was " + recorded + ", now " + actual); }
    }

    public static void main(String[] args) {
        pin("singles below minimum", legacyReorder(3, 10, 1, false), 17);
        pin("packs of six round up", legacyReorder(3, 10, 6, false), 18);
        pin("above double minimum", legacyReorder(25, 10, 6, false), 0);
        pin("singles capped at 50", legacyReorder(0, 40, 1, false), 50);
        pin("packs not capped", legacyReorder(0, 40, 25, false), 100);
        pin("clearance never reordered", legacyReorder(2, 10, 1, true), 0);
        System.out.println(failures == 0 ? "6 characterization checks hold" : failures + " checks changed");
    }
}
Output
6 characterization checks hold

What this code does

Each pin call states the behavior observed in the previous run as the recorded value, with a name that says what it describes, including the surprising uncapped packs. The program reports only behavior that has changed, so after a refactoring the output is either the single all-clear line or a list of exactly what moved. These checks are the safety net for every later change to this method.

Seams

To get a dependency out of the way in a test, you need a seam: in Feathers's words, a place where you can alter behavior in your program without editing in that place. In Java the most useful kind is the object seam, where a call goes through an object that a test can replace. A direct call to a static method such as LocalDate.now() or new SpreadsheetReader() is not a seam; nothing can be substituted. A call to a method on a field set through the constructor is a seam.

The quickest way to make one in old code, before you can restructure anything, is subclass and override method: move the awkward call into its own protected method, then in the test create a subclass that overrides it. It is not pretty, and it is meant to be temporary, but it is a tiny, safe change that gets the class under test today.

Java Example · Main.java
import java.time.*;

public class Main {
    static class LateFeeCalculator {
        long lateFeeCents(LocalDate due) {
            long daysLate = Duration.between(due.atStartOfDay(), today().atStartOfDay()).toDays();
            if (daysLate <= 0) return 0;
            return Math.min(daysLate, 5) * 1000;
        }
        protected LocalDate today() { return LocalDate.now(); }   // the seam
    }

    static class TestableCalculator extends LateFeeCalculator {
        private final LocalDate fixed;
        TestableCalculator(LocalDate fixed) { this.fixed = fixed; }
        @Override protected LocalDate today() { return fixed; }
    }

    public static void main(String[] args) {
        LocalDate due = LocalDate.of(2028, 3, 18);
        for (LocalDate day : new LocalDate[] { LocalDate.of(2028, 3, 18), LocalDate.of(2028, 3, 20), LocalDate.of(2028, 3, 31) }) {
            System.out.println("returned " + day + ": fee " + new TestableCalculator(day).lateFeeCents(due));
        }
    }
}
Output
returned 2028-03-18: fee 0
returned 2028-03-20: fee 2000
returned 2028-03-31: fee 5000

What this code does

The original rental late-fee code called LocalDate.now() in the middle of its calculation; the only change made to it is moving that call into a protected today method. The test subclass overrides today with a fixed date, so the fee can be checked for an on-time return, two days late and thirteen days late, which is capped at five days. The production class still uses the real date, unchanged in behavior.

Once tests are in place, the subclass trick can be replaced with the cleaner design from earlier lessons: pass a Clock to the constructor, as in lesson 3. Feathers calls that parameterize constructor, and it is the next most common dependency-breaking technique. Others in his catalog include extract interface, which puts an interface in front of a concrete class such as the spreadsheet reader so a fake can be used, and introduce instance delegator, which wraps a static method in an instance method so it can be replaced.

Sprout and wrap

Sometimes you need to add a feature to legacy code before you have time to get the whole method under test. Feathers offers two techniques that keep new code separate and testable even when the old code around it is not.

Sprout method: write the new behavior as a new method, test it on its own, and add a single call to it from the old code. Sprout class does the same with a new class when the old one is too tangled to touch. Wrap method: rename the old method, create a new method with the original name that calls the old one and adds the new behavior before or after, so callers get the new behavior without the old code changing. Both techniques leave the legacy code no worse and the new code fully tested.

Java Example · Main.java
import java.util.*;

public class Main {
    // legacy: big, untested, left alone except for one added line
    static List<String> buildReorderList(Map<String, int[]> stock) {
        List<String> out = new ArrayList<>();
        for (var e : stock.entrySet()) {
            int[] v = e.getValue();
            int q = v[0] < v[1] ? v[1] * 2 - v[0] : 0;
            if (q > 0) out.add(e.getKey() + " x" + q);
        }
        return withSupplierNotes(out);   // the only change: one call to the sprout
    }

    // sprout: new feature, written and tested on its own
    static List<String> withSupplierNotes(List<String> lines) {
        List<String> out = new ArrayList<>();
        for (String l : lines) out.add(l.startsWith("TUBE") ? l + " (order from Velotek)" : l + " (order from Ridgeline)");
        return out;
    }

    public static void main(String[] args) {
        System.out.println("sprout alone: " + withSupplierNotes(List.of("TUBE-700x25 x8", "BELL x4")));
        Map<String, int[]> stock = new TreeMap<>(Map.of("BELL", new int[] {1, 3}, "TUBE-700x25", new int[] {4, 10}, "LOCK-U", new int[] {6, 2}));
        System.out.println("legacy with sprout: " + buildReorderList(stock));
    }
}
Output
sprout alone: [TUBE-700x25 x8 (order from Velotek), BELL x4 (order from Ridgeline)]
legacy with sprout: [BELL x5 (order from Ridgeline), TUBE-700x25 x16 (order from Velotek)]

What this code does

The new supplier notes are written as a separate method, withSupplierNotes, which is tested on its own in the first line of output. The legacy method gains only one line, a call to the sprout on its result, so the risk of breaking it is as small as it can be. The second line shows the legacy list for bells and tubes with the new notes added, and LOCK-U left out because it is above its minimum.

Wrap method looks very similar from the outside. The difference is where the new code attaches: sprout is called from inside the old method, while wrap surrounds the old method, so the old method's body is not touched at all. Wrap is the natural choice for adding logging, timing or an audit record around an existing operation.

Strangling the old application

Rewriting CounterApp from scratch is tempting and dangerous. Big rewrites usually take far longer than planned, the old system keeps changing while the new one is built, and the shop cannot stop selling parts while it waits. Martin Fowler's strangler fig pattern (2004), named after a vine that grows around a tree until it can stand on its own, is the alternative: put a thin routing layer in front of the old application, and move features to the new code one at a time, sending each request to whichever side currently owns it. The old code shrinks until it can be deleted.

Java Example · Main.java
import java.util.*;
import java.util.function.Function;

public class Main {
    interface Feature extends Function<String, String> {}

    static final Feature legacy = req -> "legacy CounterApp handled: " + req;
    static final Map<String, Feature> rewritten = new TreeMap<>();

    static String route(String request) {
        String feature = request.split(" ")[0];
        return rewritten.getOrDefault(feature, legacy).apply(request);
    }

    public static void main(String[] args) {
        List<String> requests = List.of("sell BELL 1", "reorder all", "book Ana 10");
        System.out.println("-- week 1");
        requests.forEach(r -> System.out.println(route(r)));

        rewritten.put("reorder", req -> "new ReorderService handled: " + req);
        System.out.println("-- week 3");
        requests.forEach(r -> System.out.println(route(r)));

        rewritten.put("sell", req -> "new SellPartService handled: " + req);
        System.out.println("-- week 5");
        requests.forEach(r -> System.out.println(route(r)));
    }
}
Output
-- week 1
legacy CounterApp handled: sell BELL 1
legacy CounterApp handled: reorder all
legacy CounterApp handled: book Ana 10
-- week 3
legacy CounterApp handled: sell BELL 1
new ReorderService handled: reorder all
legacy CounterApp handled: book Ana 10
-- week 5
new SellPartService handled: sell BELL 1
new ReorderService handled: reorder all
legacy CounterApp handled: book Ana 10

What this code does

The route method sends each request to a rewritten feature if one has been registered and to the legacy code otherwise. As the weeks pass, reorder and then sell move to the new services while booking stays on the old code, and the shop keeps working throughout. When the legacy branch handles nothing, it can be deleted.

Three stages of a strangler fig migration from left to right. In week 1 a router sends every request to the large legacy CounterApp box. In week 3 the router sends reorder requests to a small new ReorderService box and the rest to legacy, which is slightly smaller. In week 5 sell and reorder go to new services and only booking goes to a much smaller legacy box.
The strangler fig: features move one at a time from the legacy code to the new design

The router is often the same kind of driving adapter lesson 8 described. In the capstone, the new CounterApp's ports will be the target, and the legacy window will be one adapter among others until it disappears.

Small, safe steps

The common thread in all of this is the size of the steps. Each change is small enough to check, either by running the characterization tests or because it is a purely mechanical refactoring, such as extract method or rename, that a modern IDE performs safely. Kent Beck put it as make the change easy, then make the easy change: first refactor so the new feature has an obvious place to go, then add it.

Version control helps too. Each small step goes in its own commit, so if a characterization test fails, the change that caused it is the last one. CounterApp itself was built last summer in a folder with no version control at all, and when a rental price went wrong in August nobody could say which day's change was responsible. Its redesign lives in the secondgear repository, where each step is expected to be a small commit that says what it did, reviewed the way Odile reviewed PR 57.

Techniques for changing legacy code
TechniqueUse whenOld code changed?
Characterization testBefore changing any untested codeNo
Subclass and override methodA call blocks testing and you need a test todayOne call moved into a method
Parameterize constructorA dependency is created inside the classConstructor gains a parameter
Extract interfaceA concrete class blocks substitutionCallers use the new interface
Sprout method or classAdding a feature to untested codeOne call added
Wrap methodAdding behavior before or after an operationMethod renamed, body untouched
Strangler figReplacing a whole application graduallyA router added in front

Try it yourself

Pin current behavior

The starter has a legacy method oldDeposit that works out a rental deposit; nobody is sure of its rules. Run it, then complete main so that it pins the three behaviors you observe with calls to pin: for 1 bike, for 3 bikes and for 5 bikes. Keep the method unchanged.

When all three pins hold, the program should print 3 results pinned.

public class Main {
    static int oldDeposit(int bikes) {
        int d = bikes * 50;
        if (bikes >= 3) d -= 25;
        if (d > 200) d = 200;
        return d;
    }

    static int failures = 0;
    static void pin(String name, int actual, int recorded) {
        if (actual != recorded) { failures++; System.out.println("CHANGED " + name + ": was " + recorded + ", now " + actual); }
    }

    public static void main(String[] args) {
        System.out.println("1 bike: " + oldDeposit(1));
        System.out.println("3 bikes: " + oldDeposit(3));
        System.out.println("5 bikes: " + oldDeposit(5));
    }
}

Try it yourself

Make a seam

The starter's ReturnDesk prints a greeting that depends on the real time, so its output cannot be checked. Move the LocalTime.now() call into a protected method now(), then write a subclass FixedDesk that overrides it to return a time given to its constructor.

The program should print Good morning, Ana for 9:30 and Good evening, Ana for 18:15.

import java.time.*;

public class Main {
    static class ReturnDesk {
        String greet(String name) {
            return (LocalTime.now().getHour() < 12 ? "Good morning, " : "Good evening, ") + name;
        }
    }

    public static void main(String[] args) {
        System.out.println(new ReturnDesk().greet("Ana").startsWith("Good") ? "greeting depends on the real clock" : "?");
    }
}

Common mistakes

  • MistakeRefactoring untested code and hoping nothing broke.

    InsteadWrite characterization tests first, then refactor under them.

  • MistakeFixing surprising behavior while adding tests.

    InsteadPin current behavior first and fix bugs as separate, deliberate changes.

  • MistakeStarting with a big restructuring to make code testable.

    InsteadUse the smallest dependency-breaking change, such as subclass and override.

  • MistakeWriting new features inside a tangled method.

    InsteadSprout a new method or class, test it alone and call it from the old code.

  • MistakePlanning a full rewrite while the shop keeps running.

    InsteadStrangle the old application feature by feature behind a router.

Summary and key terms

  • Michael Feathers defines legacy code as code without tests, because without tests no change can be checked.
  • The legacy code dilemma is that adding tests often needs changes to the code.
  • The way out is small, careful dependency-breaking changes, followed by tests and then refactoring.
  • Characterization tests record what code does now, so changes in behavior are noticed and bugs are fixed deliberately.
  • A seam is a place where behavior can be changed without editing there; in Java the object seam is the most useful.
  • Subclass and override method and parameterize constructor are quick ways to create seams.
  • Sprout method and sprout class add new, tested code with a single call from old code; wrap method adds behavior around an existing method without touching its body.
  • Martin Fowler's strangler fig pattern replaces an application gradually by routing features to new code one at a time.
  • Small steps and small commits keep every change checkable.
Legacy code
In Feathers's definition, code without tests.
Legacy code dilemma
Needing tests to change code safely, but needing to change code to add tests.
Characterization test
A test that records what code currently does, right or wrong.
Seam
A place where behavior can be changed without editing the code in that place.
Object seam
A seam where a call goes through an object that a test can replace.
Subclass and override method
Moving an awkward call into a method that a test subclass overrides.
Parameterize constructor
Passing a dependency to the constructor instead of creating it inside.
Extract interface
Putting an interface in front of a concrete class so a fake can be substituted.
Sprout method
Writing new behavior in a new, tested method called from old code.
Wrap method
Renaming a method and calling it from a new method with the old name that adds behavior.
Strangler fig
Replacing an application gradually by routing features to new code one at a time.
Change point
The place in the code where a change must be made.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. By Feathers's definition, is new code without tests legacy code?

    Show answer

    Yes; the definition is about tests, not age.

  2. A characterization test fails after a refactoring. What does it tell you?

    Show answer

    That some behavior changed, even if the old behavior was odd.

  3. Why is LocalDate.now() inside a method not a seam?

    Show answer

    Nothing can be substituted for it without editing the method.

  4. You need logging around an existing save method. Sprout or wrap?

    Show answer

    Wrap: the new behavior goes around the old method.

  5. What does the router in a strangler fig migration do?

    Show answer

    Sends each feature to the new code if it has moved, otherwise to the legacy code.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz