A burning smell from the kitchen isn't necessarily a fire. Maybe it's just toast left in too long. But you'll definitely go and check.
Code has smells like that burning smell too. A code smell is a sign in the code that deserves suspicion: not necessarily wrong, but worth checking. An anti-pattern is a solution that looks reasonable and gets used a lot, but costs more than it gives. An anti-pattern is like a recipe that looks right, but always burns the food. This lesson, the last of this track, examines Kancil Courier's old repo (the old version of its code), piece by piece: six patterns from this track, used in the wrong place.
Measuring an anti-pattern: the cost of one change
Andrew Koenig (1995) used the term anti-pattern for something that looks like a solution but isn't one. The book AntiPatterns (Brown et al., 1998) collected the most common ones, such as The Blob (the god object) and the Golden Hammer. The term code smell comes from Kent Beck, and its catalogue is in Martin Fowler's book Refactoring (1999).
How to judge one: take one realistic change, make it, then count the places changed, the files touched and the tests that fail. This table holds six changes in the old repo and in the cleaned-up version, with the same numbers as in the Lab:
| anti-pattern | change | old repo | cleaned up |
|---|---|---|---|
God facade (kancilCourier.js) |
SMS moves to WhatsApp | 3 places | 1 place |
Global singleton (trackingCounter.js) |
add a second test | 0 lines of code, 1 test fails | 0 fail |
One-partner abstract factory (partnerKit.js) |
add $5 insurance | 3 places in 3 files | 2 places in 2 files |
Know-it-all mediator (dispatch.js) |
couriers stored in a Map by id |
1 place, dispatch breaks | 1 place, 0 fail |
Speculative generality (pricing.js) |
add sameday | 3 places | 1 place |
| Golden hammer (a broker for shipping costs) | add $5 insurance | wrong total, no error | 1 place, 0 fail |
Shorter code isn't necessarily cheaper to change: the cleaned-up god facade is 24 lines and the old one 18, but the change is 1 place against 3.
God facade
kancilCourier.js holds send, refund, courierPay and monthlyReport: the work of four teams in one object. That's a god object (Brown et al. call it The Blob): one class or object that knows too much and does too much. It breaks Single Responsibility: one module, one reason to change. Messages to customers and couriers are sent directly from three methods:
smsGateway.send({ to: phone, text: trackingNo + " picked up" }) // in send
smsGateway.send({ to: phone, text: trackingNo + " refunded" }) // in refund
smsGateway.send({ to: courierPhone, text: "pay $" + parcels * 2.5 }) // in courierPay
Moving to WhatsApp changes 3 places in a file the refund, payroll and reporting teams also work on. If you miss just one, customers or couriers still get an SMS. The cure: split that object by responsibility (Shipping, Payroll, Reports), and let only one module know the vendor. After the split, the move changes only 1 line in that module:
const notifier = {
notify: (phone, message) => waApi.sendMessage(phone.replace(/^0/, "44"), message),
}
A singleton as global state
In the old repo, createTrackingNo takes the counter from a singleton. The comments below it are the results of two tests:
function createTrackingNo() {
return TrackingCounter.getInstance().next()
}
// pass: issue the first number
// fail: today's first number is KCL-0001, got KCL-0002
Adding a second test changes 0 lines of code, yet the second test fails, because the singleton keeps the count from the first test. The cure comes from the Dependency Injection lesson: the counter is passed in as a parameter, createTrackingNo(counter). main.js makes one counter for the app, and every test makes its own counter with createTrackingCounter().
An abstract factory for one family
The old partnerKit.js uses an abstract factory, though there is only one partner:
const PRODUCTS = ["createLabel", "createTracking"]
const KITS = { merpati: merpatiKit } // there is only one partner
const kit = createPartnerKit("merpati")
Adding insurance means changing 3 places in 3 files: the PRODUCTS list, merpatiKit and checkout.js. If you forget PRODUCTS, the error is kit.createInsurance is not a function. With plain functions (merpatiLabel, merpatiTracking), the code is 9 lines, not 19, and insurance is just function merpatiInsurance(p) plus one line in checkout. An abstract factory is worth it only when the second partner arrives.
A mediator that knows everything
The old dispatch.js is a mediator that reads the inside of other components directly:
const dispatch = {
selectParcel(parcel) {
const matches = courierList.items.filter((c) => c.zone === parcel.zone) // peeks inside courierList
matches.sort((a, b) => a.load - b.load)
courierList.highlighted = matches[0].id
map.pin = parcel.zone
},
}
The courier list team replaces items with byId: new Map(...) in their own file, and dispatch stops: TypeError: Cannot read properties of undefined (reading 'filter'). A mediator that knows the inside of every component has to change whenever one team changes its component, and over time it becomes a god object. The cure: dispatch only calls the components' own methods (courierList.findFor(parcel.zone), courierList.highlightCourier(courier.id), map.show(parcel.zone)), and what's inside each component is handled by that component alone.
Speculative generality
The old pricing.js has SERVICE_TYPES, a class BasePricingStrategy with options = { currency: "USD", locale: "en-US", plugins: [] } that nobody has ever used, one class per delivery service, and a PricingStrategyFactory with a registry (a list that pairs each delivery service name with its class). That's 32 lines for two rates. Adding sameday needs 3 places: a SAMEDAY entry in SERVICE_TYPES, a class SamedayPricing, and one line in the registry, which makes the code 38 lines. The table version is 4 lines and needs 1 place:
const RATES = { regular: 10, express: 18, sameday: 25 } // per kg
function calculateShipping(service, kg) {
return kg * RATES[service]
}
So it's 3 against 1. Fowler calls this speculative generality: hooks (points where extra code can be attached), parameters and parent classes for needs that are only predicted. The cure is the principle from the Which Pattern When lesson, YAGNI (You Aren't Gonna Need It). Write the simplest thing, then refactor (change how the code is arranged without changing what it does) to a pattern when the pain actually appears. YAGNI is also the right feedback for a PR (a pull request, a proposed code change) with a factory of factories of builders for an object with 2 fields.
Golden hammer
Abraham Maslow (1966) wrote that if the only tool you have is a hammer, you're tempted to treat everything as a nail. A golden hammer is one favourite tool used for every problem. At Kancil Courier, that hammer is the broker from the Pub/Sub Pattern lesson. A team that has just fallen in love with it calculates shipping costs through the broker:
broker.subscribe("calculate-shipping", (order) => {
order.shipping = order.kg * RATES[order.service]
})
function checkout(order) {
broker.publish("calculate-shipping", order)
return order.shipping
}
Insurance is added as a new subscriber in insurance.js, which loads before shipping.js because of alphabetical order. The insurance subscriber runs first, then the shipping subscriber overwrites its result: the total for a 2 kg express parcel stays $36 instead of $41, without a single error. Pub/Sub fits many parties that don't know each other. For "calculate and return the result", call a function: return calculateShipping(order) + 5 (shortened: order carries service and kg).
Code smells a machine can find
Some smells can be detected automatically from the code's text:
- Long function: a function too long to read in one pass. In the exercise, the limit is more than 20 lines.
- Magic numbers and magic strings: numbers or text with no name. In
if (user.type === 3 && order.status === "A") { discount = price * 0.15 }, the reader has to guess what3,"A"and0.15mean. The cure is named constants (fixed values with a name):const USER_TYPE_ADMIN = 3,const STATUS_ACTIVE = "A",const VIP_DISCOUNT = 0.15.parcels * 2.5in the god facade becomesparcels * PAY_PER_PARCELin its cleaned-up version. - Deep nesting: an
ifinside anifinside afor, four or more levels of braces. The cure is a guard clause, a check at the start of a function that leaves right away (if (!order) return), and splitting the code into small functions.
A detector only finds the smell. A person judges it. The regex (a text search pattern) for magic numbers also flags RATES = { express: 18 }, though that number already has a name.
Exercise: detectSmells
In the exercise, you write detectSmells(source), which takes code as a string and returns an array of smell names, sorted with sort():
"long-function"whensource.split("\n").lengthis more than 20;"magic-number"when/\b(?!0\b|1\b)\d+\b/matches (a number other than 0 and 1);"deep-nesting"when the highest{depth is 4 or more: add 1 for every{, subtract 1 for every}, keep the maximum.
The starter prints deep-nesting,long-function,magic-number for a 24-line function full of problems, an empty line for the clean add(a, b) (an empty array joins to empty text), magic-number for const x = 42, and deep-nesting for three nested ifs inside a function.
⚠️ Don't let the clean-up make new problems
- Throwing out a pattern you do need. Making one database connection only once is still right. An abstract factory is still right when the second partner arrives. Judge by the cost of change, not by the pattern's name.
- Cleaning up everything at once. Refactor in small steps, and run the tests after each one.
- In the exercise: forgetting
sort(). The order found,long-function,magic-number,deep-nesting, isn't thedeep-nesting,long-function,magic-numberthat the check expects. - In the exercise: the wrong limits. More than 20 lines (
> 20), and a depth of 4 or more (>= 4). The shortconst x = 42;may only getmagic-number.
TL;DR: An anti-pattern is a solution that looks reasonable but costs more than it gives (Koenig 1995; Brown et al. 1998). A code smell is a sign in the code worth checking (Beck and Fowler, Refactoring, 1999). Measure the cost with one real change: places changed, files touched, tests failing. A god facade is a god object (one object that knows and does too much), and it breaks Single Responsibility (one module, one reason to change). In the god facade, moving from SMS to WhatsApp changes 3 places, and only 1 once it's split up. Global singleton: the second test gets KCL-0002 because the singleton keeps the count from the first test, and the cure is DI (Dependency Injection). An abstract factory for one partner: 19 lines against 9 lines of plain functions. A mediator that reads the inside of other components directly breaks when those components change. Speculative generality (code for needs that are only predicted): sameday needs 3 places, against 1 line in RATES, and the cure is YAGNI (don't build something for a need you don't have yet). Golden hammer (one tool used for every problem): shipping costs calculated through a broker give a wrong total with no error, so just call a function. Smells a machine can find: long function (a function that is too long), magic numbers and magic strings (numbers or text with no name), and deep nesting (braces nested too deep). In the exercise, detectSmells returns an array that is sort()ed.
⚡ Measure with one change
Meaning: An anti-pattern is a solution that looks reasonable but costs more than it gives. A code smell is a sign in the code worth checking, not necessarily wrong. How to judge one: make one real change, then count the places changed, the files touched and the tests that fail.
⚡ The god object
Meaning: kancilCourier.js holds send, refund, courierPay and monthlyReport: one object that knows too much and does too much. It breaks Single Responsibility (one module, one reason to change). In that object, three methods send SMS directly, so moving to WhatsApp changes 3 places. Once the object is split by responsibility, 1 place is enough.
⚡ A forced pattern
Write:
const RATES = { regular: 10, express: 18, sameday: 25 } // per kg
function calculateShipping(service, kg) {
return kg * RATES[service]
}
Guess first: in Kancil Courier's old code, shipping costs go through a Pub/Sub broker. The shipping subscriber writes order.shipping = order.kg * RATES[order.service], and for an express parcel of 2 kg that is $36. Then $5 insurance is added as a subscriber that runs first. What's the total?
Still $36, not $41, without a single error. The shipping subscriber runs after it and overwrites the insurance result.
Meaning: This table version (RATES and calculateShipping, 4 lines) is enough for the rates, and adding sameday changes only 1 place. Write the simplest thing first (YAGNI: don't build something for a need you don't have yet). For "calculate and return the result", call a function, not a broker.