JAVA-220 · Lesson 10 of 12 · 20 min
Refactoring safely
▶ Video coming soon A video version of this lesson is on the way.
On Thursday, November 18, Ingrid opened a file that nobody at Second Gear liked to touch: RentalDesk.java, the till code for rentals. A volunteer had written it in June 2027 in a hurry before the summer rush and had since moved away. It worked, mostly, but every method was long, the variables were called t, d and y, and the price rules from lesson 6 were copied into it three times with small differences. Odile wanted the youth discount added to it properly. "Before we change what it does," Ingrid said, "we change how it is written, without changing what it does. That is refactoring, and the tests are what make it safe."
What refactoring is
Refactoring means changing the structure of code without changing its behaviour: renaming, splitting long methods, removing duplication, replacing a tangle of conditions with a clearer design. The term was popularized by Martin Fowler's book Refactoring, first published in 1999, which catalogues dozens of named refactorings, each a small, safe step. The point of refactoring is to make the next change easy. Kent Beck put it as: make the change easy, then make the easy change.
Refactoring is only safe with tests. Without them, every cleanup is a gamble that nothing changed. With them, each step is checked in seconds. That is why lessons 1 to 9 come before this one, and why the first thing Ingrid did with RentalDesk was not to edit it at all.
Code smells
A code smell is a sign in the code that something may be wrong with its design; not a bug, but a hint that the code will be hard to change. Naming smells helps a team talk about them and choose the refactoring that removes each one.
| Smell | What it looks like | Typical refactoring |
|---|---|---|
| Long method | A method that does many things over dozens of lines | Extract method |
| Duplicated code | The same rule written in several places | Extract method or extract class |
| Magic numbers | Unexplained literals such as 2500 or 7 | Introduce named constant or enum |
| Cryptic names | Variables called t, d and y | Rename |
| Primitive obsession | Strings and ints standing for bikes, money and dates | Replace with a record or enum |
| Long parameter list | Methods taking five or six loosely related values | Introduce parameter object |
| Switch on type | if or switch chains on a type code, repeated across methods | Replace conditional with an enum or polymorphism |
RentalDesk had nearly all of them. Its receipt method is shown below exactly as it was, inside a test that prints its output for a set of cases.
Characterization tests first
Michael Feathers, in Working Effectively with Legacy Code, defines legacy code simply as code without tests. His first step for changing it is a characterization test: a test that records what the code does now, whether or not that is what anyone intended. You run the existing code on a range of inputs, capture the outputs and turn them into expected values. The characterization tests then guard every refactoring step: if an output changes, the refactoring changed behaviour.
public class Main {
static String receipt(String bike, int d, boolean y, int late) {
long t = 0;
if (bike.equals("CITY")) t = 2500 * (d / 7 * 5 + d % 7);
else if (bike.equals("CARGO")) t = 4000 * (d / 7 * 5 + d % 7);
else if (bike.equals("TANDEM")) t = 4500 * (d / 7 * 5 + d % 7);
if (y && d < 7) t = t - t * 10 / 100;
if (late > 0) t = t + late * 1000;
String s = bike + " " + d + "d";
if (y) s = s + " youth";
if (late > 0) s = s + " late " + late;
return s + " = " + t / 100 + "." + (t % 100 < 10 ? "0" : "") + t % 100;
}
public static void main(String[] args) {
String[][] cases = {
{"CITY", "3", "false", "0"}, {"CITY", "7", "false", "0"}, {"CARGO", "2", "true", "0"},
{"TANDEM", "9", "false", "2"}, {"CITY", "1", "true", "1"}, {"CARGO", "14", "true", "0"},
};
for (String[] c : cases) {
System.out.println(receipt(c[0], Integer.parseInt(c[1]), Boolean.parseBoolean(c[2]), Integer.parseInt(c[3])));
}
}
}CITY 3d = 75.00 CITY 7d = 125.00 CARGO 2d youth = 72.00 TANDEM 9d late 2 = 335.00 CITY 1d youth late 1 = 32.50 CARGO 14d youth = 400.00
What this code does
The legacy method is called on six cases chosen to touch every branch: each bike, weekly rentals, the youth discount and late returns. Its output is recorded as it is, without judging it, and becomes the expected result for every refactoring step that follows. One line already looks suspicious, the cargo bike for 14 days with no youth discount, but a characterization test records behaviour first and asks questions later.
Reading the recorded output with Odile turned up one surprise: the youth discount applies only to rentals under seven days. Odile confirmed that this was intended, because weekly rentals already have their own discount. If she had said it was a bug, Hamza would still have refactored first, keeping the behaviour, and fixed the bug afterwards as a separate, deliberate change with its own new test. Mixing refactoring and behaviour changes is how bugs get into cleanups.
import java.util.*;
public class Main {
static String receipt(String bike, int d, boolean y, int late) {
long t = 0;
if (bike.equals("CITY")) t = 2500 * (d / 7 * 5 + d % 7);
else if (bike.equals("CARGO")) t = 4000 * (d / 7 * 5 + d % 7);
else if (bike.equals("TANDEM")) t = 4500 * (d / 7 * 5 + d % 7);
if (y && d < 7) t = t - t * 10 / 100;
if (late > 0) t = t + late * 1000;
String s = bike + " " + d + "d";
if (y) s = s + " youth";
if (late > 0) s = s + " late " + late;
return s + " = " + t / 100 + "." + (t % 100 < 10 ? "0" : "") + t % 100;
}
// The characterization test: expected lines captured from the legacy code.
static final List<String> EXPECTED = List.of(
"CITY 3d = 75.00", "CITY 7d = 125.00", "CARGO 2d youth = 72.00",
"TANDEM 9d late 2 = 335.00", "CITY 1d youth late 1 = 32.50", "CARGO 14d youth = 400.00");
public static void main(String[] args) {
String[][] cases = {
{"CITY", "3", "false", "0"}, {"CITY", "7", "false", "0"}, {"CARGO", "2", "true", "0"},
{"TANDEM", "9", "false", "2"}, {"CITY", "1", "true", "1"}, {"CARGO", "14", "true", "0"},
};
int failures = 0;
for (int i = 0; i < cases.length; i++) {
String[] c = cases[i];
String actual = receipt(c[0], Integer.parseInt(c[1]), Boolean.parseBoolean(c[2]), Integer.parseInt(c[3]));
if (!actual.equals(EXPECTED.get(i))) {
failures++;
System.out.println("CHANGED case " + i + ": expected <" + EXPECTED.get(i) + "> but was <" + actual + ">");
}
}
System.out.println(failures == 0 ? "Nothing changed: all " + cases.length + " cases match" : failures + " case(s) changed");
}
}Nothing changed: all 6 cases match
What this code does
The six expected lines were copied from the previous run's output, which turns the recording into a test. Run against the untouched legacy code, every case matches, as it must. From now on, after every small refactoring step, this same check runs, and any CHANGED line means the last step altered behaviour and should be undone.
Small steps
Refactoring is done in small steps, each one leaving the code compiling and the tests passing. Hamza worked through RentalDesk like this, running the characterization test after every step and committing to Git after every green run.
- Rename t, d, y and late to total, days, youth and daysLate (the IDE's Rename refactoring updates every use at once).
- Extract the repeated weekly rule into a method chargedDays(days).
- Replace the bike name strings and rates with an enum, Bike, holding each daily rate.
- Extract the youth discount and late fee into small named methods.
- Extract the money formatting into the shared Money class from core, which already has tests.
Modern IDEs automate the mechanical refactorings, such as rename, extract method, extract variable, inline and change signature, and do them correctly across the whole project, including in tests. IntelliJ IDEA's Refactor menu and VS Code's refactoring actions are much safer than editing by hand, because they understand the code rather than its text. Hamza used the IDE for every rename and extraction, and the characterization test for everything else.
import java.util.*;
public class Main {
enum Bike {
CITY(2500), CARGO(4000), TANDEM(4500);
final long dailyCents;
Bike(long dailyCents) { this.dailyCents = dailyCents; }
}
static final int YOUTH_DISCOUNT_PER_100 = 10;
static final long LATE_FEE_PER_DAY_CENTS = 1000;
static int chargedDays(int days) { return days / 7 * 5 + days % 7; }
static long youthDiscount(long rent, boolean youth, int days) {
return youth && days < 7 ? rent * YOUTH_DISCOUNT_PER_100 / 100 : 0;
}
static long lateFee(int daysLate) { return Math.max(0, daysLate) * LATE_FEE_PER_DAY_CENTS; }
static String money(long cents) { return String.format("%d.%02d", cents / 100, cents % 100); }
static String receipt(Bike bike, int days, boolean youth, int daysLate) {
long rent = bike.dailyCents * chargedDays(days);
long total = rent - youthDiscount(rent, youth, days) + lateFee(daysLate);
String label = bike + " " + days + "d" + (youth ? " youth" : "") + (daysLate > 0 ? " late " + daysLate : "");
return label + " = " + money(total);
}
static final List<String> EXPECTED = List.of(
"CITY 3d = 75.00", "CITY 7d = 125.00", "CARGO 2d youth = 72.00",
"TANDEM 9d late 2 = 335.00", "CITY 1d youth late 1 = 32.50", "CARGO 14d youth = 400.00");
public static void main(String[] args) {
String[][] cases = {
{"CITY", "3", "false", "0"}, {"CITY", "7", "false", "0"}, {"CARGO", "2", "true", "0"},
{"TANDEM", "9", "false", "2"}, {"CITY", "1", "true", "1"}, {"CARGO", "14", "true", "0"},
};
int failures = 0;
for (int i = 0; i < cases.length; i++) {
String[] c = cases[i];
String actual = receipt(Bike.valueOf(c[0]), Integer.parseInt(c[1]), Boolean.parseBoolean(c[2]), Integer.parseInt(c[3]));
if (!actual.equals(EXPECTED.get(i))) {
failures++;
System.out.println("CHANGED case " + i + ": expected <" + EXPECTED.get(i) + "> but was <" + actual + ">");
}
}
System.out.println(failures == 0 ? "Nothing changed: all " + cases.length + " cases match" : failures + " case(s) changed");
}
}Nothing changed: all 6 cases match
What this code does
After the refactoring, each rule has a name: the weekly rule, the youth discount, the late fee and the money format are separate small methods, and the rates live in the Bike enum instead of three copied lines. The receipt method now reads almost like Odile's price sheet. The characterization test still passes on all six cases, which is the proof that none of this changed a single receipt.
The refactored code is longer in lines but far shorter in ideas, and each idea can now be unit-tested on its own. Adding Odile's change, which turned out to be raising the youth discount to 15 in 100, became a one-line edit to a named constant, followed by an update to the two expected lines it affects, both reviewed with Odile.
A refactoring that went wrong
Small steps matter because even simple-looking changes can alter behaviour. During the session Hamza tried a tidy-up that looked harmless, applying the youth discount after adding the late fee instead of before. The characterization test caught it immediately.
public class Main {
static long before(long rent, boolean youth, int days, long late) {
long discount = youth && days < 7 ? rent * 10 / 100 : 0;
return rent - discount + late;
}
static long after(long rent, boolean youth, int days, long late) {
long total = rent + late;
long discount = youth && days < 7 ? total * 10 / 100 : 0; // the "tidy-up"
return total - discount;
}
public static void main(String[] args) {
long[][] cases = {{7500, 0, 3, 0}, {2500, 1, 1, 1000}, {8000, 1, 2, 0}};
for (long[] c : cases) {
boolean youth = c[1] == 1;
long b = before(c[0], youth, (int) c[2], c[3]);
long a = after(c[0], youth, (int) c[2], c[3]);
System.out.printf("rent %d youth %-5s late %4d: before %d, after %d %s%n", c[0], youth, c[3], b, a, a == b ? "" : "<- CHANGED");
}
}
}rent 7500 youth false late 0: before 7500, after 7500 rent 2500 youth true late 1000: before 3250, after 3150 <- CHANGED rent 8000 youth true late 0: before 7200, after 7200
What this code does
Moving the discount after the late fee gives the same answer whenever there is no late fee, so most cases pass and the change looks safe. For a youth rental returned late, the discount is now taken off the late fee too, and the total drops from 3250 to 3150 cents. The characterization case CITY 1d youth late 1 was chosen to touch both rules at once, which is exactly why it caught the change.
Hamza reverted the step with one Git command and moved on. Without the characterization test, the shop would have quietly undercharged late youth rentals, a bug that might have taken months to notice.
Try it yourself
Extract a method
The weekly rule, five days charged for each full week plus the leftover days, is written out twice in rent. Extract it into a method chargedDays(int days) and call it in both places, without changing any output.
The program should print CITY 9d: 17500, CARGO 14d: 40000 and then unchanged.
public class Main {
static long rent(String bike, int days) {
if (bike.equals("CARGO")) return 4000L * (days / 7 * 5 + days % 7);
return 2500L * (days / 7 * 5 + days % 7);
}
public static void main(String[] args) {
String a = "CITY 9d: " + rent("CITY", 9);
String b = "CARGO 14d: " + rent("CARGO", 14);
System.out.println(a);
System.out.println(b);
boolean extracted = false;
System.out.println(a.equals("CITY 9d: 17500") && b.equals("CARGO 14d: 40000") && extracted ? "unchanged" : "not finished");
}
}Try it yourself
Replace a string with an enum
rate decides a daily rate by comparing strings, and a typo such as "Cargo" silently gets the city rate. Replace the strings with an enum Bike with constants CITY(2500), CARGO(4000) and TANDEM(4500), each holding its rate, and change main to use it.
The program should print 2500 4000 4500.
public class Main {
static long rate(String bike) {
if (bike.equals("CARGO")) return 4000;
if (bike.equals("TANDEM")) return 4500;
return 2500;
}
public static void main(String[] args) {
System.out.println(rate("CITY") + " " + rate("Cargo") + " " + rate("TANDEM"));
}
}Common mistakes
MistakeRefactoring code that has no tests.
InsteadWrite characterization tests first, recording what the code does now.
MistakeFixing bugs in the middle of a refactoring.
InsteadKeep behaviour identical while refactoring; fix bugs afterwards as separate changes with their own tests.
MistakeTaking large refactoring steps.
InsteadMake one small change, run the tests, commit, and repeat.
MistakeRenaming and extracting by hand with search and replace.
InsteadUse the IDE's automated refactorings, which understand the code.
MistakeJudging legacy output while characterizing it.
InsteadRecord behaviour as it is first, then ask the owner which parts are bugs.
Summary and key terms
- Refactoring changes the structure of code without changing its behaviour, to make the next change easy, and it is only safe with tests.
- Code smells such as long methods, duplicated code, magic numbers, cryptic names, primitive obsession, long parameter lists and repeated switches on type point to refactorings such as extract method, rename, introduce constant, replace with an enum or record and introduce parameter object.
- Legacy code, code without tests, is first covered by characterization tests that record its current outputs.
- Refactoring then proceeds in small steps, each followed by the tests and a commit, using the IDE's automated refactorings where possible.
- Behaviour changes and bug fixes are kept separate from refactoring.
- A characterization case that touches several rules together catches subtle reorderings.
- Refactoring
- Changing the structure of code without changing its behaviour.
- Code smell
- A sign in the code that its design may make it hard to change.
- Legacy code
- In Michael Feathers's definition, code without tests.
- Characterization test
- A test that records what existing code does now, used to guard changes.
- Extract method
- Moving a piece of code into a new, named method and calling it.
- Magic number
- An unexplained literal value in code, such as 2500 or 7.
- Primitive obsession
- Using strings and numbers for concepts that deserve their own types.
- Introduce parameter object
- Replacing several related parameters with one object or record.
- Automated refactoring
- An IDE operation, such as Rename, that changes code correctly everywhere it is used.
Practice problems
Work each problem on paper first, then reveal the answer to check.
What is the difference between refactoring and fixing a bug?
Show answer
Refactoring keeps behaviour the same; fixing a bug changes it on purpose.
What is a characterization test?
Show answer
A test that records the current outputs of existing code, whatever they are.
Why use the IDE's Rename instead of search and replace?
Show answer
It understands the code and updates every real use, and only those.
Why did Hamza revert the step that moved the discount after the late fee?
Show answer
The characterization test showed it changed the total for late youth rentals.
What smell does a variable called t show?
Show answer
A cryptic name, fixed with the Rename refactoring.
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.