You tidy the checkout function in one sitting: rename things, move numbers into constants, split it into small functions. Then cart D gives a different result. Out of dozens of changes, which one caused it? Hard to find.
That's why refactoring happens in small steps that have names. Refactoring is changing the structure of code without changing its result, and each step is checked before you continue. It's like tidying the storeroom of Raka's T-Shirt Shop. You don't take every shelf apart in one day. You move one shelf, then try to pick the four items people order most. If you still find all four, you continue with the next shelf. If something is missing, you know exactly which shelf caused it. In code, moving one shelf is one refactoring step.
The rule: small steps, same result
In our code, the "four items people order most" are the four carts in the first lesson's Lab. They are checked with the check function, which prints OK when the result is the one it should be, and DIFF when it is different:
function check(actual, expected) {
console.log(actual === expected ? 'OK ' + actual : 'DIFF ' + actual + ', expected ' + expected);
}
check(calculateTotal(cartA, 'SAVE10'), 'Total: $220.50');
check(calculateTotal(cartA, ''), 'Total: $245.00');
check(calculateTotal(cartC, ''), 'Total: $90.00');
check(calculateTotal(cartD, 'SAVE10'), 'Total: $204.00');
Before the first step, all four are OK. After every step, all four must stay OK. If one says DIFF, the cause is the last step, because that's the only thing that changed.
Six steps from calc(k, v)
The messy checkout function from the first lesson, calc(k, v), is tidied with six techniques that have names:
| Step | Technique | What changes | 4 carts |
|---|---|---|---|
| 1 | Rename | calc, k, v, t become calculateTotal, cart, voucherCode, total |
OK |
| 2 | Replace Magic Number with Symbolic Constant | 0.1, 200, 15 become named constants |
OK |
| 3 | Extract Variable | the shipping condition gets the name needsShipping |
OK |
| 4 | Extract Function | split into calculateSubtotal, applyVoucher, addShipping, formatPrice |
OK |
| 5 | Inline Variable | needsShipping is merged back into addShipping |
OK |
| 6 | Replace Conditional with Lookup | if (voucherCode === 'SAVE10') becomes a VOUCHERS table |
OK |
Each OK in this table means the four carts were run after that step and gave the same results. The sections below show each technique, and the mistake that most often happens with it.
Rename and Replace Magic Number
Rename changes a name and every use of it at the same time. If one t is left behind in if (t < 200), the first check stops right away with Uncaught ReferenceError: t is not defined, because the name t no longer exists.
Replace Magic Number with Symbolic Constant gives a magic number (a number in code with no explanation) a name:
const VOUCHER_DISCOUNT = 0.1;
const FREE_SHIPPING_MIN = 200;
const SHIPPING_FEE = 15;
Say you mistype FREE_SHIPPING_MIN = 20, one zero short. Of the four carts, how many catch that mistake: zero, two, or four? Guess first, then look at the result:
OK Total: $220.50
OK Total: $245.00
DIFF Total: $75.00, expected Total: $90.00
DIFF Total: $189.00, expected Total: $204.00
Two carts catch it, C and D. A ($245 and $220.50) is above both $200 and $20, so A can't tell the two minimums apart. C and D are below $200 but above $20, so shipping isn't added and the mistake shows right away.
Extract Variable and Inline Variable
Extract Variable gives an expression (a piece of code that produces a value) a name, so the code reads like a sentence:
if (voucherCode === 'SAVE10') total = total - total * VOUCHER_DISCOUNT;
const needsShipping = total < FREE_SHIPPING_MIN;
if (needsShipping) total = total + SHIPPING_FEE;
Another common example: if (user.age >= 18 && user.hasID && !user.isBanned) becomes const isEligibleForAccess = user.age >= 18 && user.hasID && !user.isBanned;. Be careful where you put needsShipping. If needsShipping is declared (created) before the voucher line, its value comes from the total before the discount. Cart D ($210 before the voucher) is above the minimum, so shipping isn't added and the result is Total: $189.00.
Inline Variable is the reverse: if a name adds no meaning, merge it back into its expression. After step 4, needsShipping is inside a function named addShipping. The function's name already says that shipping is added, so if (amount < FREE_SHIPPING_MIN) return amount + SHIPPING_FEE; is clear enough. Extract and Inline are both refactors. Pick the one that makes the code easier to read in that spot.
Extract Function
Extract Function moves one block of code into a named function, as in the Small, Focused Functions lesson:
function calculateTotal(cart, voucherCode) {
let total = calculateSubtotal(cart);
total = applyVoucher(total, voucherCode);
total = addShipping(total);
return 'Total: ' + formatPrice(total);
}
The typical mistake here: forgetting to pass a parameter. applyVoucher(total) without voucherCode means the voucher is never used: A + SAVE10 becomes $245.00 and D becomes $210.00, two DIFFs.
Replace Conditional with Lookup
A condition that picks a value by a key can be replaced with a table: an object that pairs each key with its value. Here the key is the voucher code and the value is the discount rate, so the if/else if chain is gone:
const VOUCHERS = { SAVE10: 0.1 };
function applyVoucher(amount, voucherCode) {
const rate = Object.hasOwn(VOUCHERS, voucherCode) ? VOUCHERS[voucherCode] : 0;
return amount - amount * rate;
}
Object.hasOwn(VOUCHERS, voucherCode)checks whether the code is really written in the table. If it is,VOUCHERS[voucherCode]takes its rate. If not,''included, the rate is 0. So an unknown code still gets no discount, exactly as before.- Why not
VOUCHERS[voucherCode] ?? 0, which uses 0 when the left value isnullorundefined? Because the buyer types the voucher code, and every object has built-in keys such astoStringandconstructor.VOUCHERS['toString']is a function, notundefined, so?? 0does nothing and the total is$NaN. Try it yourself: run a cart with the voucher codetoString. - The table's keys must match exactly:
{ save10: 0.1 }in lower case makes A + SAVE10 and D come outDIFF. - A new voucher later is one line in the table. But adding a voucher is a feature, so do it after the refactor is finished, in a separate commit (one saved change in git).
Exercise: getDiscount
In the exercise, getDiscount(type, price) uses an if/else if chain. Replace it with a DISCOUNT_RATES table: regular 0, member 0.1, vip 0.2, employee 0.3. The function returns price * (1 - rate). An unknown type gets the rate 0 through Object.hasOwn(DISCOUNT_RATES, type), as with the vouchers above, with not a single else if. The output:
100
90
80
70
100
⚠️ Steps too big, tests too few
- Refactoring and adding a feature at the same time. If the result changes, you can't tell which one caused it. Refactor until all four carts are
OK, commit, then add the feature. - Big steps. Six techniques at the same time, then a
DIFF: you can't tell which technique caused it. Do one step, then check. - Refactoring without tests. Without the four carts, the zero missing from
20is only found when buyers complain. - Tests that never touch the threshold. No cart's total is exactly $200, the free-shipping minimum and the only number where
<and<=differ. So if<turns into<=, all four stayOK. Add a cart right at the minimum. - In the exercise, leaving an
else if. The whole condition chain has to go, so the table does the work.
TL;DR: Refactoring changes the structure of code without changing its result, in small steps that have names. Each step is checked with the four carts in the first lesson's Lab: their results must stay the same (OK). The messy checkout function calc(k, v) is tidied in six steps: Rename (change names), Replace Magic Number with Symbolic Constant (numbers become named constants, FREE_SHIPPING_MIN), and Extract Variable (an expression, a piece of code that produces a value, gets a name: needsShipping, isEligibleForAccess). Then Extract Function (a block moves into a function), Inline Variable (a name is merged back into its expression), and Replace Conditional with Lookup (an if becomes a table, an object that pairs each voucher code with its rate). The table is read through Object.hasOwn(VOUCHERS, voucherCode), because ?? 0 (use 0 when the value is null or undefined) fails for the voucher code toString. A mistake appears at the step it happens in: a leftover old name t gives a ReferenceError (an error for a name that doesn't exist); a minimum of 20 (one zero short) is caught by carts C and D; a parameter not passed is caught by A + SAVE10 and D. Tests only catch mistakes at the numbers they test, so add a cart whose total is exactly the free-shipping minimum. Don't mix refactoring with new features. In the exercise: a DISCOUNT_RATES table with employee: 0.3, no else if, output 100, 90, 80, 70, 100.
⚡ Small steps, same result
Write:
check(calculateTotal(cartA, 'SAVE10'), 'Total: $220.50');
check(calculateTotal(cartD, 'SAVE10'), 'Total: $204.00');
Meaning: check compares the result of the checkout function calculateTotal with the result it should be, then prints OK or DIFF. This code checks two of the four carts in the first lesson's Lab (A and D). Refactoring is changing the structure of code without changing its result, in small steps that have names. After every step, all four carts must stay OK. If one says DIFF, the cause is the last step.
⚡ Tests only catch what they touch
Guess first: the free-shipping minimum should be $200, but you mistype FREE_SHIPPING_MIN = 20, one zero short. The totals before shipping: cart A is $245 ($220.50 with the voucher), C is $75, and D is $189 after the voucher. Of the four carts, how many catch that mistake?
Two, C and D. A is above both $200 and $20, so A can't tell the two minimums apart. C and D are below $200 but above $20, so shipping isn't added and the mistake shows right away.
Meaning: Tests only catch mistakes at the numbers they test. Add a cart whose total is right at the minimum.
⚡ Extract Variable
Write:
const isEligibleForAccess = user.age >= 18 && user.hasID && !user.isBanned;
Meaning: Extract Variable gives an expression (a piece of code that produces a value) a name, so the code reads like a sentence. In this code, a long condition that used to sit inside an if gets the name isEligibleForAccess. In the checkout function, the shipping condition total < FREE_SHIPPING_MIN gets the name needsShipping. Be careful where you put it: a needsShipping declared before the voucher line works from the total before the voucher discount.
⚡ Replace Conditional with Lookup
Write:
const VOUCHERS = { SAVE10: 0.1 };
function applyVoucher(amount, voucherCode) {
const rate = Object.hasOwn(VOUCHERS, voucherCode) ? VOUCHERS[voucherCode] : 0;
return amount - amount * rate;
}
Meaning: The if/else if chain becomes a table: the object VOUCHERS, which pairs each voucher code with its rate. Object.hasOwn checks whether the voucher code is really written in the table. So a voucher code that isn't in the table, toString included (a built-in key of every object), still gets no discount, exactly as before. In the exercise, a DISCOUNT_RATES table replaces every else if.