Every time Raka creates a new kind of voucher, which checkout functions do you have to open? Right now the checkout is like someone holding a long notebook: "if the voucher is a percentage type, calculate it like this; if it's a cut of a fixed amount, like that; if it's free shipping, something else". Every new kind of voucher means rewriting the notebook. It is much easier if every voucher card carries its own rule on the back. The cashier just says "card, calculate your discount".
A change that size is done with refactoring patterns: larger refactorings with names. In the Refactoring Techniques lesson you tidied the inside of one function. Here you move responsibilities between functions and classes. The rule stays the same: the structure changes, the result doesn't, checked with the test carts.
Three kinds of voucher, two places asking "which kind?"
The VOUCHERS table from the Refactoring Techniques lesson only holds percentage rates. ADR-0002 in the Documentation as Code lesson already recorded its limit: a $25 cut doesn't fit. Raka now has three kinds: SAVE10 (10%), CUT25 (a $25 cut) and FREESHIP (free shipping). The first idea is to give each voucher a type (its kind), then ask about it with a switch:
const VOUCHERS = {
SAVE10: { type: 'percent', value: 0.1 },
CUT25: { type: 'fixed', value: 25 },
FREESHIP: { type: 'shipping' },
};
function applyVoucher(amount, voucherCode) {
const voucher = VOUCHERS[voucherCode];
if (!voucher) return amount;
switch (voucher.type) {
case 'percent': return amount - amount * voucher.value;
case 'fixed': return Math.max(0, amount - voucher.value);
default: return amount;
}
}
function addShipping(amount, voucherCode) {
const voucher = VOUCHERS[voucherCode];
if (voucher && voucher.type === 'shipping') return amount;
if (amount < FREE_SHIPPING_MIN) return amount + SHIPPING_FEE;
return amount;
}
Math.max(0, ...) keeps the discounted amount from going below 0. The four old carts plus two new checks: cart C ($75) with CUT25 becomes Total: $65.00, with FREESHIP Total: $75.00. All six are OK. But the knowledge about voucher kinds is spread over two functions: the switch in applyVoucher and the if in addShipping. These two places are the checkout's notebook.
Replace Conditional with Polymorphism
Every kind of voucher becomes its own class, with the same methods: apply(amount) for the discount and shipping(amount) for the shipping fee. Polymorphism means different objects are called the same way, and each answers with its own rule. These voucher objects are the cards that carry their own rule:
class NoVoucher {
apply(amount) { return amount; }
shipping(amount) { return amount < FREE_SHIPPING_MIN ? SHIPPING_FEE : 0; }
}
class PercentVoucher extends NoVoucher {
constructor(rate) { super(); this.rate = rate; }
apply(amount) { return amount - amount * this.rate; }
}
class FixedVoucher extends NoVoucher {
constructor(cut) { super(); this.cut = cut; }
apply(amount) { return Math.max(0, amount - this.cut); }
}
class FreeShippingVoucher extends NoVoucher {
shipping() { return 0; }
}
const VOUCHERS = {
SAVE10: new PercentVoucher(0.1),
CUT25: new FixedVoucher(25),
FREESHIP: new FreeShippingVoucher(),
};
function calculateTotal(cart, voucherCode) {
const voucher = Object.hasOwn(VOUCHERS, voucherCode) ? VOUCHERS[voucherCode] : new NoVoucher();
const discounted = voucher.apply(calculateSubtotal(cart));
return 'Total: ' + formatPrice(discounted + voucher.shipping(discounted));
}
NoVoucherholds the behaviour without a voucher: no discount, normal shipping. A voucher code that isn't in the table usesNoVoucherthroughObject.hasOwn. If it were written with?? new NoVoucher(), the codetoString(a built-in key of every object) would get a function, notNoVoucher, andcalculateTotalwould stop with aTypeError.- Each subclass (a class made with
extends) only overrides (writes its own version of) the method whose rule differs fromNoVoucher.FreeShippingVoucherdoesn't rewriteapply. In a subclass's constructor,super()must be called beforethisis used, andthis.ratekeeps the rate in that object. calculateTotalhas noswitchand notypeat all. It just says "voucher, calculate".- All six checks stay
OK. This is a refactor, not a feature.
This refactor also contains a second one, Move Function: the "free shipping?" check moves from addShipping into FreeShippingVoucher.shipping, next to the data it uses. A function belongs near the data it touches most.
The fourth kind: SHIP5
Raka asks for a fourth kind of voucher, SHIP5: shipping costs only $5. Before you continue, guess: how many existing functions do you have to change in the switch version, and how many in the class version?
In the switch version, SHIP5 needs one line in the table and one existing function changed: addShipping gets a new branch. applyVoucher needs no change, but you have to read it first to know that. If addShipping is missed, there's no error. Here is the check for cart C with SHIP5:
DIFF Total: $90.00, expected Total: $80.00
In the class version, zero existing functions change. You add one new class, CheapShippingVoucher, that only overrides shipping with amount < FREE_SHIPPING_MIN ? 5 : 0, and one line SHIP5: new CheapShippingVoucher() in the table.
So it's one against zero, and all seven checks are OK. SHIP5's rule lives in one place, so there is no branch to miss. Adding a new kind without changing old functions is also what the Open/Closed principle in the next lesson means. The classic example has the same shape: if (shape.type === 'circle') ... else if (shape.type === 'square') becomes classes Circle and Square, each with its own area().
Introduce Parameter Object
A shipping label needs a name, an address and a phone number. Three strings in a row are easy to swap, and JavaScript doesn't complain:
function shippingLabel(name, address, phone) {
return 'To: ' + name + ', ' + address + ' (' + phone + ')';
}
shippingLabel('7 Coffee St', 'Sari', '0812-1111-2222');
// To: 7 Coffee St, Sari (0812-1111-2222)
Introduce Parameter Object joins data that is always used together into one object:
function shippingLabel(customer) {
return 'To: ' + customer.name + ', ' + customer.address + ' (' + customer.phone + ')';
}
const sari = { name: 'Sari', address: '7 Coffee St', phone: '0812-1111-2222' };
shippingLabel(sari); // To: Sari, 7 Coffee St (0812-1111-2222)
The order of the properties no longer matters. If you want to add a note for the courier, only the object and the function that uses it change. Another function that only passes the object along to shippingLabel also keeps its signature (the line with a function's name and parameters).
Exercise: refactorings an editor does
Some refactorings are mechanical enough for a tool to do. VS Code has Rename Symbol (F2) and Extract Function, and a linter marks functions nobody uses. In the exercise, three functions imitate these refactorings on a string of code:
extractMethod(code, methodName)is already in the editor. It wraps the code as`function ${methodName}() {\n ${code}\n}`. In the editor, themethodNamepassed in is'calculateSum', so the result containsfunction calculateSumandincludesprintstrue.renameVariable(code, oldName, newName)usescode.replace(new RegExp('\\b' + oldName + '\\b', 'g'), newName).\bis a word boundary, so only the whole worddis replaced. Thegflag replaces all of them, not only the first.'let d = d + da;'becomes'let day = day + da;'. Without\b, you getlet day = day + daya;. Withoutg, only the firstdchanges.removeDeadCode(functions, usedFunctions)usesfunctions.filter(fn => usedFunctions.includes(fn)): only the functions that are used remain, in the original list's order.(['a', 'b', 'c'], ['c', 'a'])becomes["a","c"].
The exercise's output is three lines: true, const currentDate = new Date();, and ["fetchUser","formatDate"].
When to refactor: after green
Martin Fowler, in Refactoring (second edition, 2018), defines refactoring as a change to the internal structure of code. It makes the code easier to understand and cheaper to modify, without changing its observable behaviour. So refactoring is not rewriting from scratch, not adding a feature, and not making the program faster.
In TDD (Test-Driven Development, Kent Beck, 2002), the order is Red, Green, Refactor:
- Write a test that fails (red).
- Make it pass the simplest way (green).
- Then tidy the code.
You refactor after green, because at that point the tests prove the behaviour is right and guard every step. The switch version above also passed the six checks first, and only then was split into classes.
⚠️ What makes a big refactor messy
- Refactoring while adding a voucher kind. Split the switch into classes until all six checks are
OK, commit, then addSHIP5. - Turning every switch into classes. A switch that appears once and rarely grows is easier to read than five classes. Polymorphism is worth it when the "which kind?" question appears in several places.
- A subclass that rewrites every method. If
FreeShippingVoucheralso copiesapply, the discount rule is in two places again. - In the exercise, renaming without
\bor withoutg./d/gbreaksdaintodaya, andreplace('d', ...)only replaces the first one. - In the exercise, reordering.
removeDeadCodefiltersfunctions, notusedFunctions, so the order stays["a","c"].
TL;DR: Refactoring patterns are larger refactorings with names: responsibilities move between functions and classes without changing the result. They are checked with the test carts, and done after the tests are green, that is, passing, in the order Red, Green, Refactor: a failing test, a passing test, then tidying. Replace Conditional with Polymorphism: three voucher kinds asked about in applyVoucher's switch and addShipping's if become classes PercentVoucher, FixedVoucher, FreeShippingVoucher. Each class has the methods apply (the discount) and shipping (the shipping fee), so each voucher object answers with its own rule (polymorphism). All six cart checks (four old, two new) stay OK, and a fourth kind, SHIP5 (shipping for just $5), changes zero existing functions. In the switch version, SHIP5 needs one existing function changed, and if that change is missed, cart C gives $90.00 instead of $80.00. Move Function moves a function to the data it uses. Introduce Parameter Object replaces three parameters (name, address, phone), which are easy to mix up, with one customer object. Refactoring is a change to structure without changing observable behaviour (Fowler). In the exercise: extractMethod wraps code in function name(), renameVariable uses replace with \b (a word boundary) and g (replace all), and removeDeadCode uses filter, keeping the original order. The output is true, const currentDate = new Date();, ["fetchUser","formatDate"].
⚡ Two places asking "which kind?"
Write:
switch (voucher.type) {
case 'percent': return amount - amount * voucher.value;
case 'fixed': return Math.max(0, amount - voucher.value);
default: return amount;
}
Meaning: Here each voucher has a type (its kind), and applyVoucher uses a switch to ask about it: percent or fixed (a cut of a fixed amount). addShipping asks again with an if: is it the free-shipping kind? The results are right and all six cart checks (four old, two new) are OK. But the knowledge about voucher kinds is spread over two functions, so every new kind has to be remembered in two places.
⚡ Replace Conditional with Polymorphism
Write:
class FreeShippingVoucher extends NoVoucher {
shipping() { return 0; }
}
Meaning: Every voucher kind becomes a class with the same methods, apply (the discount) and shipping (the shipping fee). Polymorphism means different objects are called the same way, and each answers with its own rule. FreeShippingVoucher is a subclass of NoVoucher (no voucher, normal shipping) and only writes its own version of the method that differs: shipping is always 0. calculateTotal just says "voucher, calculate", with no switch at all.
⚡ The fourth kind: SHIP5
Guess first: Raka asks for a SHIP5 voucher, shipping for just $5. How many existing functions change in the switch version, and how many in the class version?
One against zero. In the switch version, addShipping gets a new branch. If it's missed, cart C ($75) gives $90.00 instead of $80.00. In the class version it's one new class, CheapShippingVoucher, plus one line in the table.
Meaning: Refactoring changes the internal structure of code without changing its observable behaviour. The order is Red, Green, Refactor: a failing test (red), a passing test (green), then tidy the code. So you refactor after the tests are green, and don't mix it with a new feature.
⚡ Introduce Parameter Object
Write:
function shippingLabel(customer) {
return 'To: ' + customer.name + ', ' + customer.address + ' (' + customer.phone + ')';
}
Meaning: The shipping label function used to take three strings in a row, (name, address, phone), which are easy to swap, and JavaScript doesn't complain. One customer object makes the order irrelevant.