Skip to lesson

Safe refactoring with tests and IDE tools

ShopLite's shipping code has no tests and nobody remembers every rule. You want to tidy it, but a "small tidy-up" that changes a price is the kind of mistake customers notice first.

Refactoring: same behaviour, better structure

Refactoring is changing the structure of code without changing what it does: for every input, the output stays exactly the same.

Every step in this lesson makes one promise: no input gives a different answer afterwards. Test that promise on four changes.

Done safely, refactoring is a series of tiny, tested steps. Done unsafely, it is a rewrite that quietly changes prices, totals or messages that customers rely on.

The rest of this lesson gives you the safety net: tests first, then the IDE's own refactorings, then small steps with a commit after each.

Predict the output

Refactoring or not?

Decide for each change: does any input now give a different result?

Round 1 of 4

Move the Phone class to another package with the IDE.

-import com.shoplite.util.Phone;
+import com.shoplite.customer.Phone;

Tests first: characterisation tests

A characterisation test records what code does today, found by running it, not what a specification says it should do. It fails if a refactoring changes any result.

Example 1 checks the legacy shippingCost with seven inputs. Example 2 writes the same checks as a JUnit 5 test.

Example 1 · Characterisation checks for legacy shipping code

CharacterisationDemo.javaJava
public class CharacterisationDemo {    // Legacy code from shoplite-console: no tests, nobody remembers every rule.    static int shippingCost(int g, String pin, boolean exp) {        int c = 40;        if (g > 500) c = c + ((g - 500) / 500 + 1) * 20;        if (pin.startsWith("79")) c = c + 50;        if (exp) c = c * 2;        if (g == 0) c = 0;        return c;    }
    static int passed = 0;    static int failed = 0;
    /** A characterisation check: "expected" is what the code does TODAY, found by running it. */    static void check(String name, int expected, int actual) {        if (expected == actual) {            passed++;            System.out.println("PASS " + name);        } else {            failed++;            System.out.println("FAIL " + name + ": expected " + expected + " but was " + actual);        }    }
    public static void main(String[] args) {        check("500 g, standard area         -> 40", 40, shippingCost(500, "560038", false));        check("501 g, one extra slab        -> 60", 60, shippingCost(501, "560038", false));        check("1000 g, two slabs (odd!)     -> 80", 80, shippingCost(1000, "560038", false));        check("1001 g                       -> 80", 80, shippingCost(1001, "560038", false));        check("remote area adds 50          -> 90", 90, shippingCost(500, "793001", false));        check("express doubles everything   -> 180", 180, shippingCost(500, "793001", true));        check("0 g (e-book), even express   -> 0", 0, shippingCost(0, "560038", true));        System.out.println(passed + " passed, " + failed + " failed");    }}
Output
PASS 500 g, standard area         -> 40
PASS 501 g, one extra slab        -> 60
PASS 1000 g, two slabs (odd!)     -> 80
PASS 1001 g                       -> 80
PASS remote area adds 50          -> 90
PASS express doubles everything   -> 180
PASS 0 g (e-book), even express   -> 0
7 passed, 0 failed

What this code does

  • Every expected value came from running the old method once. Together they pin down each rule: the 500 g slab, the remote-area charge, the express doubling and the 0 g case.
  • The 1000 g result (two slabs) looks like a bug, but the test keeps it. A refactoring must not change it; a separate, deliberate fix may.

Example 2 · src/test/java/com/shoplite/shipping/ShippingCostCharacterisationTest.java

Runs in: a Maven project with JUnit 5

Java
// src/test/java/com/shoplite/shipping/ShippingCostCharacterisationTest.javapackage com.shoplite.shipping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;
/** * Pins down what ShippingCalculator does TODAY, before we refactor it. * Values were found by running the old code, not by reading a specification. */class ShippingCostCharacterisationTest {
    private final ShippingCalculator calculator = new ShippingCalculator();
    @ParameterizedTest(name = "{0} g to {1}, express={2} -> Rs {3}")    @CsvSource({            "500,  560038, false, 40",            "501,  560038, false, 60",            "1000, 560038, false, 80",    // odd: 1000 g counts as two slabs. Kept as is; asked the product owner.            "1001, 560038, false, 80",            "500,  793001, false, 90",            "500,  793001, true,  180",            "0,    560038, true,  0"    })    void keepsTodaysShippingCost(int grams, String pincode, boolean express, int expectedRupees) {        assertEquals(expectedRupees, calculator.shippingCost(grams, pincode, express));    }}
Sample output
$ mvn -q test -Dtest=ShippingCostCharacterisationTest
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.061 s -- in com.shoplite.shipping.ShippingCostCharacterisationTest

What this code does

  • The same checks as a JUnit 5 parameterised test: one row per case, and the display name shows the inputs if a row fails.
  • The comment on the 1000 g row tells the next reader that the odd value is known and kept on purpose.

You cannot refactor safely without tests, and legacy code often has none. Pick inputs around every rule and boundary (500 g, 501 g, 1000 g, a remote pincode, express, 0 g), run the old code and write the results down as expected values.

If a result looks wrong, keep it in the test anyway and ask about it: fixing it is a separate change. A common mistake is to edit an expected value "because it looks wrong" in the middle of a refactoring.

Predict the output

Find today's value

Run the legacy rule by hand. The result is what the test must expect, odd or not.

Round 1 of 3

What does it cost for 501 g, standard area, not express?

int cost = 40;
if (grams > 500) cost = cost + ((grams - 500) / 500 + 1) * 20;

IDE refactorings: rename, extract, inline, move

An automated refactoring is a change the IDE makes for you while keeping the code compiling and behaving the same, such as Rename, Extract method, Inline or Move.

Example 3 shows shippingCost after four IDE refactorings: rename, extract constant, extract method and inline.

Example 3 · shippingCost after rename, extract constant, extract method and inline

IdeRefactoringsDemo.javaJava
public class IdeRefactoringsDemo {    static final int BASE_CHARGE = 40;    static final int SLAB_GRAMS = 500;    static final int CHARGE_PER_SLAB = 20;    static final String REMOTE_AREA_PREFIX = "79";    static final int REMOTE_AREA_CHARGE = 50;
    static int shippingCost(int grams, String pincode, boolean express) {        if (grams == 0) {            return 0;                       // e-books and gift cards: nothing to ship        }        int cost = BASE_CHARGE + extraWeightCharge(grams) + remoteAreaCharge(pincode);        return express ? cost * 2 : cost;    }
    static int extraWeightCharge(int grams) {        if (grams <= SLAB_GRAMS) {            return 0;        }        return ((grams - SLAB_GRAMS) / SLAB_GRAMS + 1) * CHARGE_PER_SLAB;   // behaviour kept, odd 1000 g case too    }
    static int remoteAreaCharge(String pincode) {        return pincode.startsWith(REMOTE_AREA_PREFIX) ? REMOTE_AREA_CHARGE : 0;    }
    public static void main(String[] args) {        for (int grams : new int[] {500, 501, 1000, 1001}) {            System.out.println(grams + " g: Rs " + shippingCost(grams, "560038", false));        }        System.out.println("500 g remote, express: Rs " + shippingCost(500, "793001", true));        System.out.println("0 g express: Rs " + shippingCost(0, "560038", true));    }}
Output
500 g: Rs 40
501 g: Rs 60
1000 g: Rs 80
1001 g: Rs 80
500 g remote, express: Rs 180
0 g express: Rs 0

What this code does

  • Four IDE refactorings made this: Rename (g to grams, exp to express), Extract Constant (40, 500, 20, "79", 50), Extract Method (extraWeightCharge, remoteAreaCharge) and Inline Variable (a temporary used once). The method still gives the same six answers, including the odd 1000 g one.
  • The method now reads as the rule: base charge plus weight and remote-area charges, doubled for express, with e-books free.

Rename updates every use of a name. Extract method and extract variable give a block or an expression a name. Inline does the opposite for a name that no longer helps. Move puts a method or class where it belongs and fixes the imports.

The IDE understands Java, so it will not miss a call in another file or rename a different variable with the same name, as find-and-replace would. When unsure, IntelliJ's Refactor This menu (Ctrl+Alt+Shift+T on Windows, Ctrl+T on macOS) lists every refactoring that fits the cursor.

Small steps with tests green, and a commit after each

A safe refactoring step is one tiny change, such as one rename or one extract, followed by a test run, and a commit when the tests are green.

After each small step, run the tests. Green: commit. Red: undo only that step.

Terminal
mvn -q test                                # green? then:git add -Agit commit -m "refactor(shipping): rename variables in ShippingCalculator"# red? throw away this one step:git restore .
The safe refactoring loop. Start with the tests green. Make one small change, such as a rename or an extract. Run the tests. If they are green, commit and go back for the next small change. If a test is red, undo that one step and try a smaller step. Never move on while a test is red.

Example 4 · Four small steps, the tests green after each

SmallStepsDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
public class SmallStepsDemo {    interface Shipping {        int cost(int grams, String pincode, boolean express);    }
    static int v0(int g, String pin, boolean exp) {        int c = 40;        if (g > 500) c = c + ((g - 500) / 500 + 1) * 20;        if (pin.startsWith("79")) c = c + 50;        if (exp) c = c * 2;        if (g == 0) c = 0;        return c;    }
    static int v1(int grams, String pincode, boolean express) {        int cost = 40;        if (grams > 500) cost = cost + ((grams - 500) / 500 + 1) * 20;        if (pincode.startsWith("79")) cost = cost + 50;        if (express) cost = cost * 2;        if (grams == 0) cost = 0;        return cost;    }
    static int v2(int grams, String pincode, boolean express) {        int cost = 40 + extraWeight(grams) + remoteArea(pincode);        if (express) cost = cost * 2;        if (grams == 0) cost = 0;        return cost;    }
    static int v3(int grams, String pincode, boolean express) {        if (grams == 0) {            return 0;        }        int cost = 40 + extraWeight(grams) + remoteArea(pincode);        return express ? cost * 2 : cost;    }
    static int extraWeight(int grams) {        return grams > 500 ? ((grams - 500) / 500 + 1) * 20 : 0;    }
    static int remoteArea(String pincode) {        return pincode.startsWith("79") ? 50 : 0;    }
    /** The characterisation suite from Example 1, run against any version. */    static int passing(Shipping s) {        int[][] numbers = {{500, 0, 40}, {501, 0, 60}, {1000, 0, 80}, {1001, 0, 80}, {500, 1, 90}, {500, 2, 180}, {0, 3, 0}};        int pass = 0;        for (int[] n : numbers) {            String pincode = n[1] == 1 || n[1] == 2 ? "793001" : "560038";            boolean express = n[1] >= 2;            if (s.cost(n[0], pincode, express) == n[2]) {                pass++;            }        }        return pass;    }
    public static void main(String[] args) {        Map<String, Shipping> steps = new LinkedHashMap<>();        steps.put("step 0 legacy code       ", SmallStepsDemo::v0);        steps.put("step 1 rename            ", SmallStepsDemo::v1);        steps.put("step 2 extract methods   ", SmallStepsDemo::v2);        steps.put("step 3 guard clause first", SmallStepsDemo::v3);        steps.forEach((name, version) ->                System.out.println(name + " -> " + passing(version) + "/7 green, commit"));    }}
Output
step 0 legacy code        -> 7/7 green, commit
step 1 rename             -> 7/7 green, commit
step 2 extract methods    -> 7/7 green, commit
step 3 guard clause first -> 7/7 green, commit

What this code does

  • Each version is one small step from the one before, and the same seven characterisation checks run against every version.
  • In a real project each step is a commit. If step 3 had gone red, you would undo only step 3, not the whole morning's work.

Small commits make code review easy and give you safe points to return to. A refactoring commit contains only refactoring, with a message such as refactor(shipping): extract weight and remote-area charges.

Example 4 runs the same seven checks on four versions of shippingCost, each one small step from the one before.

Order of execution

One safe step

Put one turn of the refactoring loop in order.

Refactoring vs changing behaviour

A behaviour change is any change after which some input gives a different output, even when it fixes a bug. It is not a refactoring and gets its own commit.

Example 5 compares the shipping rule before and after a "tidy-up" that also fixed the 1000 g case.

Example 5 · A "tidy-up" that changed prices

BehaviourChangeDemo.javaJava
public class BehaviourChangeDemo {    static int extraWeightToday(int grams) {        return grams > 500 ? ((grams - 500) / 500 + 1) * 20 : 0;    }
    // During a "refactoring", someone also "fixed" the 1000 g case in the same commit.    static int extraWeightTidiedAndFixed(int grams) {        return grams > 500 ? ((grams - 1) / 500) * 20 : 0;    }
    public static void main(String[] args) {        int[] weights = {501, 999, 1000, 1001, 1500};        int differences = 0;        for (int g : weights) {            int before = extraWeightToday(g);            int after = extraWeightTidiedAndFixed(g);            String verdict = before == after ? "same" : "CHANGED";            if (before != after) {                differences++;            }            System.out.printf("%5d g: before Rs %d, after Rs %d  %s%n", g, before, after, verdict);        }        System.out.println(differences + " of " + weights.length + " weights changed:"                + " a behaviour change, not a refactoring");    }}
Output
  501 g: before Rs 20, after Rs 20  same
  999 g: before Rs 20, after Rs 20  same
 1000 g: before Rs 40, after Rs 20  CHANGED
 1001 g: before Rs 40, after Rs 40  same
 1500 g: before Rs 60, after Rs 40  CHANGED
2 of 5 weights changed: a behaviour change, not a refactoring

What this code does

  • The new formula is arguably right for 1000 g, but it also changes 1500 g, which nobody asked for. Customers would see new prices with no announcement.
  • A characterisation test catches it at once. The right way: finish the refactoring with all tests green, then make the fix in its own commit with the expected values changed on purpose.

Mixing both in one commit hides the fix inside a large tidy-up and makes a later bug hard to trace.

Keep two hats and wear one at a time: the refactoring hat (tests unchanged, all green) and the feature or bug-fix hat (change a test first, then the code). The odd 1000 g shipping price is fixed in its own commit, with its test updated on purpose.

Next step

Check your understanding

12 quick questions