A refactoring round hands you code that works and is hard to change, and asks you to improve it. It tests something different from a design round: not whether you can invent a clean structure from nothing, but whether you can change a messy structure without breaking it. Interviewers watch your process more than your result. This lesson gives the method, then applies it to one realistic example, with every step tested. The principles behind the target design are in the SOLID lesson and the patterns lessons.
1. The Rules of Safe Refactoring
- Refactoring changes structure, never behaviour. A change that alters an output is a bug fix or a feature. Keep it out of a refactoring step, and do it in a separate step.
- Pin the behaviour first. Without tests you cannot know a step was safe. If there are none, write tests that record what the code does now (characterization tests), even where the result looks wrong.
- Small steps, tests green after each. If a step fails, you undo one small change instead of hunting through a large one.
- One kind of change at a time. Rename, extract, move or replace. Never two together.
- Say what you are doing and why. "This is a switch on type, so I will move the data into an enum." The commentary is half of what is graded.
flowchart LR
A[Run tests: green] --> B[One small change]
B --> C[Run tests]
C -->|green| D[Commit]
C -->|red| E[Undo the change]
D --> B
E --> B
2. The Code We Are Given
A price calculator. The rules: 10% off a line for 10 or more units, 20% for 50 or more, but never for books. Then a customer discount (VIP 10%, MEMBER 5%), then a coupon (SAVE10 takes 10% off orders of 5000 or more, FREESHIP waives shipping). Shipping is 499 below 5000. Amounts are in cents.
class LegacyPriceCalculator {
public long total(String customer, List<Line> lines, String coupon) {
long sum = 0;
for (Line l : lines) {
long t = l.unitCents() * l.qty();
if (!l.category().equals("BOOK")) {
if (l.qty() >= 50) t = t * 80 / 100;
else if (l.qty() >= 10) t = t * 90 / 100;
}
sum += t;
}
if (customer.equals("VIP")) sum = sum * 90 / 100;
else if (customer.equals("MEMBER")) sum = sum * 95 / 100;
if (coupon != null && coupon.equals("SAVE10") && sum >= 5000) sum = sum * 90 / 100;
long shipping = 499;
if (sum >= 5000 || "FREESHIP".equals(coupon)) shipping = 0;
return sum + shipping;
}
}
It works, and it is typical: strings compared in if chains, rules mixed into one loop, magic numbers, and no place to add a rule. The task will be: gift cards must get no bulk or customer discount. Today that means editing two nested conditions and hoping.
3. Step 0: Pin the Behaviour
Write tests for every rule, and for the surprises. One surprise here: SAVE10 can push an order from exactly 5000 down to 4500, which is below the free-shipping line, so the customer pays shipping and the total is 4999. That looks like a bug. In a refactoring round you do not fix it: you pin it, flag it, and leave it.
class PriceCalculatorTest {
private final PriceCalculator calc = new PriceCalculator();
private long total(String customer, String coupon, Line... lines) {
return calc.total(customer, List.of(lines), coupon);
}
@Test void exactlyFiftyDollarsShipsFree() {
assertEquals(5000, total("REGULAR", null, new Line("GENERAL", 1000, 5)));
}
@Test void booksNeverGetBulkDiscount() {
assertEquals(10000, total("REGULAR", null, new Line("BOOK", 1000, 10)));
}
@Test void vipGetsTenPercentOffAfterBulk() {
assertEquals(8100, total("VIP", null, new Line("GENERAL", 1000, 10)));
}
@Test void roundingIsDownAtEachStep() {
assertEquals(1439, total("MEMBER", null, new Line("GENERAL", 990, 1)));
}
@Test void couponCanDropOrderBelowFreeShipping() {
assertEquals(4999, total("REGULAR", "SAVE10", new Line("GENERAL", 1000, 5)));
}
// ... one test per rule
}
Then add a golden master test: keep the old class beside the new one, and compare them on tens of thousands of generated orders.
class GoldenMasterTest {
@Test void refactoredCodeMatchesTheLegacyCodeOnEveryCombination() {
var legacy = new LegacyPriceCalculator();
var fresh = new PriceCalculator();
String[] customers = {"REGULAR", "MEMBER", "VIP", "GOLD", "vip"};
String[] coupons = {null, "SAVE10", "FREESHIP", "OTHER"};
String[] categories = {"GENERAL", "BOOK", "TOY"};
int[] quantities = {1, 2, 9, 10, 11, 49, 50, 51};
long[] prices = {1, 99, 999, 1000, 4999, 5000};
int checked = 0;
for (String customer : customers)
for (String coupon : coupons)
for (String c1 : categories) for (int q1 : quantities) for (long p1 : prices)
for (String c2 : categories) for (int q2 : new int[]{1, 10, 50}) {
List<Line> lines = List.of(new Line(c1, p1, q1), new Line(c2, 1000, q2));
assertEquals(legacy.total(customer, lines, coupon), fresh.total(customer, lines, coupon),
customer + " " + coupon + " " + lines);
checked++;
}
}
}
The two kinds of test catch different mistakes. When I deliberately broke the finished code in 11 ways, the hand-written tests caught all 11, and the golden master caught 7. It missed bugs in the coupon threshold, the free-shipping boundary and gift cards, because its inputs never reach those values. The golden master is wide and shallow, and the hand-written tests are narrow and sharp. Use both, and run them after every step.
4. The Steps
- Extract methods. Move the loop body into
lineTotal, the customer chain intocustomerDiscount, the coupon intoapplyCoupon, and shipping intoshipping. No logic changes, andtotalnow reads as four lines of intent. - Name the magic numbers.
499and5000becomeSHIPPINGandFREE_SHIPPING_FROM. Five copies of the same percentage arithmetic become onepercentOff(x, 10), with the rounding (round down) kept exactly. - Replace strings with types.
"VIP"becomesCustomer.VIPin an enum that holds its own percentage, and the if-chain disappears. Unknown names keep mapping toREGULAR, because that is today's behaviour and the tests pin it. - Move the rule next to its data. "Books get no bulk discount" is a property of a category, so it becomes a flag on a
Categoryenum, and the bulk tiers move beside it.Linenow knows its own total. - Turn the coupon into a type. A
Couponenum answers two questions: what it does to the sum (applyTo) and whether it waives shipping.
After each step: run the tests, and commit. The final code:
enum Category {
GENERAL(true, true), BOOK(false, true), GIFTCARD(false, false);
final boolean bulkDiscount, customerDiscount;
Category(boolean bulkDiscount, boolean customerDiscount) {
this.bulkDiscount = bulkDiscount;
this.customerDiscount = customerDiscount;
}
static Category of(String name) {
try { return valueOf(name); } catch (IllegalArgumentException e) { return GENERAL; }
}
int bulkPercent(int qty) {
if (!bulkDiscount) return 0;
return qty >= 50 ? 20 : qty >= 10 ? 10 : 0;
}
}
enum Customer {
REGULAR(0), MEMBER(5), VIP(10);
final int percentOff;
Customer(int percentOff) { this.percentOff = percentOff; }
static Customer of(String name) {
try { return valueOf(name); } catch (IllegalArgumentException e) { return REGULAR; }
}
}
enum Coupon {
NONE, SAVE10, FREESHIP;
static Coupon of(String code) {
try { return code == null ? NONE : valueOf(code); } catch (IllegalArgumentException e) { return NONE; }
}
long applyTo(long sum) {
return this == SAVE10 && sum >= 5000 ? PriceCalculator.percentOff(sum, 10) : sum;
}
boolean waivesShipping() { return this == FREESHIP; }
}
record Line(String category, long unitCents, int qty) {
long total() {
long base = unitCents * qty;
return PriceCalculator.percentOff(base, Category.of(category).bulkPercent(qty));
}
}
class PriceCalculator {
private static final long SHIPPING = 499, FREE_SHIPPING_FROM = 5000;
long total(String customer, List<Line> lines, String couponCode) {
long eligible = 0, other = 0;
for (Line line : lines) {
if (Category.of(line.category()).customerDiscount) eligible += line.total();
else other += line.total();
}
long sum = percentOff(eligible, Customer.of(customer).percentOff) + other;
Coupon coupon = Coupon.of(couponCode);
sum = coupon.applyTo(sum);
return sum + shipping(sum, coupon);
}
private long shipping(long sum, Coupon coupon) {
return sum >= FREE_SHIPPING_FROM || coupon.waivesShipping() ? 0 : SHIPPING;
}
static long percentOff(long amount, int percent) {
return amount * (100 - percent) / 100;
}
}
5. The Feature Arrives
Now the real task: gift cards get no bulk or customer discount. In the original this meant editing two nested conditions. Here it is one enum constant, GIFTCARD(false, false), plus splitting the sum into lines that can take the customer discount and lines that cannot. Write the tests for it first (giftCardsGetNoBulkOrCustomerDiscount and a mixed order): they fail until the change is made. That is the point of refactoring first: the new rule costs a few lines because the structure was made ready for it.
6. Smells and the Moves That Fix Them
| Smell | What you see | Move |
|---|---|---|
| Long method | One method doing several jobs, with comments marking the sections | Extract method, named for the intent |
| Primitive obsession | Strings and ints for customers, categories, money | Enum or small type that carries its own data |
| Switch or if-chain on type | The same if (x.equals(...)) repeated in several places |
Enum with data, or polymorphism (strategy) when the behaviour differs |
| Magic numbers | Unexplained 499, 5000, * 90 / 100 |
Named constants, one helper |
| Duplicated logic | Near-identical blocks with different numbers | Extract the shared part, pass the difference in |
| Feature envy | Code that reads another object's fields to decide something | Move the method to the object that owns the data |
| Hidden dependency | Static calls, new inside methods, a global clock or session |
Pass it in through the constructor, behind an interface, so tests can replace it |
7. Running It in a 45-Minute Round
- First 5 minutes: read the code and ask what must not change.
- Next 10: tests, either run the existing ones or write them.
- Next 20: the refactoring steps, smallest first.
- Last 10: the new requirement, then a summary of what you would do with more time.
8. The Checklist: Go in This Order
Keep this list in mind during the round. Each item is one thing to say or do.
- Read the code aloud and say in one sentence what it does.
- Ask what must not change: public methods, output format, rounding, odd cases. Ask whether tests exist and how much time you have.
- Name the smells you see (table in section 6) and state your plan in three lines.
- Check the tests. Run the existing ones. If there are none, write characterization tests from the rules.
- Cover the edges: zero, exact thresholds, the largest and smallest values, unknown inputs, and the odd cases from step 2.
- Add a golden master if the input space is wide: old and new code compared on many generated inputs.
- Pin, flag and leave bugs. Write a test that records the current result and say it looks wrong. Do not fix it now.
- Start from a green baseline. All tests pass before the first change. Commit.
- Take the safest steps first: rename, extract method, name the magic numbers.
- Then the structural steps: replace strings with types, move rules next to their data, remove duplication, wrap static calls and
newbehind interfaces. - After every step: run the tests, commit, and say what you changed and why. One kind of change per step.
- Keep the public API stable until the end. Change signatures last and on purpose.
- Do the new requirement last: write the failing test, then make the small change.
- Re-check: tests green, golden master equal, no output changed. Read the final code once.
- Close with a summary: what you changed, the bugs you flagged, and what you would do next.
If time runs out, stop at a green state and go straight to step 15. A smaller refactoring that passes its tests beats a larger one that does not.
9. Common Pitfalls
- Fixing bugs while refactoring. You can no longer tell which change did what. Note the bug, and change it separately.
- Refactoring without tests. Everything after that is a guess.
- A big-bang rewrite. It looks impressive and cannot be checked. Small steps can.
- Over-engineering. Three enums were enough here. A factory, a rule engine and an interface per discount would add classes without removing a smell.
- Changing the public API in step one. Callers and tests break at once. Keep signatures stable until the end, then change them deliberately.
- Silent rounding changes. Integer arithmetic order matters.
(a * 90 / 100)per line and per order give different cents, which is why the tests pin them. - Not explaining. Correct steps taken in silence leave the interviewer guessing.
10. Interview Questions and Answers
- Where do you start with code that has no tests? With characterization tests: call the code, record its outputs, and assert them, including odd ones. They protect every later step.
- What is the difference between refactoring and rewriting? Refactoring is a sequence of small behaviour-preserving steps, each checked by tests. A rewrite replaces the code at once and cannot be checked step by step.
- You find a bug while refactoring. What do you do? Add a test that documents it, finish the current step, and fix it as a separate change, so the diff shows which change altered behaviour.
- When is an enum enough, and when do you need strategy classes? Enums with data cover rules that differ only by numbers or flags. Use strategy classes when the behaviour itself differs and may grow.
- How do you refactor code with static calls and singletons? Create a seam: wrap the static call in a small interface, pass it in through the constructor, and use a fake in tests. Do it with automated IDE refactorings where possible, so the change itself is safe.
- How do you know you are done? The tests pass, the new requirement fits in a few lines, and each class has one reason to change. More cleanup after that has diminishing returns.