There's a checkout file that still runs and passes every test, yet nobody dares to change it. If the code is right, why is everyone afraid to touch it?
Usually because of a code smell: a sign on the surface of the code that points to a deeper problem, code that is expensive to change. The term was popularised by Kent Beck and Martin Fowler in the "Bad Smells in Code" chapter of Refactoring (1999). Some names in this lesson's table, for example Mysterious Name and Repeated Switches, come from the second edition (2018). In that edition, Replace Magic Number with Symbolic Constant is called Replace Magic Literal. It's like a strange smell from the fridge. It doesn't prove anything has gone bad, but it is reason enough to open it and check. Smells work the same way: not a bug, but an invitation to look closer, and every smell has a name and its own refactoring cure.
old-checkout.js
This file was found in an old folder of Raka's T-Shirt Shop, from before this track began. It is still used, and still works:
const report = []; // pretend report file
const outbox = []; // pretend email outbox
function processOrder(name, email, address, phone, k, v) {
// check email
if (email.indexOf('@') < 0) return 'Bad email';
// calculate total
let t = 0;
for (let i = 0; i < k.length; i++) {
t = t + k[i].price * k[i].qty;
}
if (v == 'SAVE10') {
t = t - t * 0.1;
} else if (v == 'CUT25') {
t = t - 25;
}
if (t < 200) {
t = t + 15;
}
// send email
outbox.push(email + ': Total $' + t.toFixed(2));
// save report
report.push(name + ', ' + address + ', ' + phone + ': $' + t.toFixed(2));
return 'Total: $' + t.toFixed(2);
}
function shippingLabel(name, address, phone) {
return 'To: ' + name + ', ' + address + ' (' + phone + ')';
}
function calcOldDiscount(t) {
return t * 0.15;
}
A smell is not a bug
Run the test carts through processOrder:
OK Total: $220.50
OK Total: $245.00
OK Total: $90.00
OK Total: $204.00
OK Total: $65.00
None say DIFF. The results are right; what's wrong is the cost of changing it. A smell is an indication, not a bug, and sometimes that shape is still right for its context: a small switch in a simple parser, or a long function that is just a straight sequence of steps. The deciding question: is this code still easy to change tomorrow?
A catalogue from one file
Eleven smells in old-checkout.js, each with the change it makes expensive and its cure from an earlier lesson:
| Smell | In old-checkout.js | Change it makes expensive | Cure |
|---|---|---|---|
| Long Function | processOrder, 22 lines |
every change means reading all of it | Extract Function |
| Long Parameter List | 6 parameters | the order is easy to swap | Introduce Parameter Object |
| Data Clumps | name, address, phone always together, in two functions |
adding a postcode changes every signature | Introduce Parameter Object |
| Magic Number | 0.1, 25, 200, 15 |
changing the shipping threshold: which number? | Replace Magic Number with Symbolic Constant |
| Duplicated Code | toFixed(2) 3 times |
changing the price format: 3 lines | Extract Function (formatPrice) |
| Repeated Switches | if (v == 'SAVE10') ... else if |
a new voucher edits this function | Lookup table or Polymorphism |
| Primitive Obsession | email is just a string, checked with indexOf('@') |
the email rule changes: find every check | Replace Primitive with Object |
| Divergent Change | processOrder changes for 5 reasons |
the email greeting opens the price formula | Split by reason (SRP) |
| Mysterious Name | k, v, t |
every reader guesses | Rename |
| Comments | // check email, // calculate total |
comments patching missing names | Extract a named function |
| Dead Code | calcOldDiscount, never called |
read and maintained for nothing | Remove Dead Code |
One side effect shows up in the test too: the five price checks above send 5 emails and write 5 report lines, exactly the symptom from the Single Responsibility lesson.
Pairs that get mixed up
- Shotgun Surgery: one small change forces you to edit many places, like a shotgun blast spreading its pellets. The price format here is 3 lines in one function; in a bigger shop, a report format rewritten in 6 different files means 6 files touched for one change. The cure is Move Function: gather it into one place.
- Divergent Change: the opposite. One function or class changes for many different reasons.
processOrderis changed by finance, the warehouse, customer service and IT. The cure is splitting it by reason. - Data Clumps vs Primitive Obsession: Data Clumps are several pieces of data that always travel together (
name, address, phone). Primitive Obsession is a domain concept stored as a basic type (stringfor an email,numberfor money), so its validation and formatting get scattered. - Feature Envy: a function that uses another object's data more than its own. The cure is Move Function into that object.
Primitive Obsession and Value Objects
An email as a string means every place that receives one has to remember to check it. Replace Primitive with Object makes a value object: a small object that carries a value and its own rules.
class Email {
constructor(text) {
if (!text.includes('@')) throw new Error('Invalid email: ' + text);
this.text = text;
}
}
new Email('[email protected]'); // passes
new Email('sari-mail.com'); // Error: Invalid email: sari-mail.com
The email rule now lives in one place, and a function that receives an Email knows its contents were checked. Money can get the same treatment: a Price with a format() method.
Machines find some of them
Three smells can be counted: the number of parameters, numbers in the code, the number of lines. The exercise's detector, run on the three functions of old-checkout.js:
processOrder ["long-parameter-list","magic-number","long-function"]
shippingLabel []
calcOldDiscount ["magic-number"]
The rest need a person. shippingLabel is clean to the machine, yet its name, address, phone is a Data Clump. Shotgun Surgery, Divergent Change and Feature Envy only show when you ask "what changes together?". Even 0.1 slips past, because the pattern \b\d+\b splits it into 0 and 1, two numbers ignored on purpose. Tools like ESLint catch what can be counted; review catches the rest.
Exercise: detectSmells
detectSmells(fnString) takes a function's code as a string and returns an array of smell names, in this order:
"long-parameter-list": more than 3 parameters. Take what's inside the first parentheses afterfunctionwith/function\s*\w*\s*\(([^)]*)\)/, split it withsplit(','), drop the empty ones, count."magic-number": there is a number other than0and1.fnString.match(/\b\d+\b/g) || [], thenfilterthe ones that aren't'0'or'1'."long-function": more than 20 lines,fnString.split('\n').length > 20.
Each one found is pushed onto smells. The output:
["long-parameter-list","magic-number"]
[]
["magic-number","long-function"]
fn1 has 4 parameters and 42; fn2 is clean; fn3 has 28 lines and 99. Other functions with the same signs must be recognised too: function f(a,b,c,d) { return 7; } gets two smells, function g(a) { return a + 1; } gets none.
⚠️ A smell isn't always rot
- Treating a smell as a bug. All five checks are
OK. A smell points at the cost of change, not at a wrong result. - Fixing every smell right now. Tidy what sits on the path of the next change;
calcOldDiscountcan just be deleted, and a smallswitchthat never grows can stay. - Mixing up Shotgun Surgery and Divergent Change. One change, many places: shotgun. One place, many reasons: divergent.
- Trusting the detector fully.
shippingLabelpasses and0.1passes. Machines count; people ask "what changes together?". - In the exercise, the order or the numbers 0 and 1. The order is parameters, numbers, length;
0and1are not magic numbers, sofunction g(a) { return a + 1; }must be[].
TL;DR: A code smell is a sign of code that is expensive to change, not a bug (Kent Beck and Martin Fowler, Refactoring, 1999): old-checkout.js with eleven smells still passes all five checks. The catalogue: Long Function and Comments (Extract Function), Long Parameter List and Data Clumps (Introduce Parameter Object), Magic Number (named constants), Duplicated Code (formatPrice), Repeated Switches (a table or Polymorphism), Primitive Obsession (a value object like Email), Divergent Change (split by reason), Mysterious Name (Rename), Dead Code (delete it). Shotgun Surgery: one change touches many places, like a report format in 6 files; Divergent Change: one place changes for many reasons. Machines only find what can be counted. In the exercise: detectSmells returns long-parameter-list (> 3 parameters), magic-number (a number other than 0 and 1) and long-function (> 20 lines) in that order, with the output ["long-parameter-list","magic-number"], [], ["magic-number","long-function"].
⚡ A smell is not a bug
Meaning: A code smell is a sign on the surface of the code pointing to code that is expensive to change. old-checkout.js has eleven smells, yet all five checks stay OK. The deciding question: is this code still easy to change tomorrow?
⚡ One line, three smells
Write:
function processOrder(name, email, address, phone, k, v) {
Meaning: Six parameters is a Long Parameter List, name, address, phone always travelling together is a Data Clump, and k, v are Mysterious Names. The cures come from earlier lessons: Introduce Parameter Object and Rename.
⚡ Shotgun Surgery or Divergent Change
Guess first: one small change to the report format forces you to edit 6 different files. Which smell is that?
Shotgun Surgery: one change, many places. The opposite is Divergent Change: one place that changes for many reasons, like processOrder.
Meaning: The cure for Shotgun Surgery is Move Function, gathering it into one place. Divergent Change gets split by reason.
⚡ A value object for Primitive Obsession
Write:
class Email {
constructor(text) {
if (!text.includes('@')) throw new Error('Invalid email: ' + text);
this.text = text;
}
}
Meaning: An email as a plain string means every place has to remember to check it. A value object carries the value and its rules, so the email rule lives in one place.