Learn Why Clean Code

Clean code is code that people can read easily and change safely. The computer doesn't care about names: the checkout function calc(k, v) and its clean…

Your mother leaves you a shopping note: "sgr 2, egs 10, oil 1". She understands the note, because she wrote it. You, standing at the shelf, have to guess: 2 kilos of sugar? 10 eggs? 1 litre of oil? Code is often like that note: its writer understands it, and its reader has to guess. The computer doesn't care whether a variable is called k or cart. But a person who reads the code has to guess what each abbreviation means.

Clean code is code that other people can read easily and change safely. "Other people" includes you, six months from now. This track teaches clean code through one example that is tidied a little at a time.

The example for this whole track: the checkout at Raka's T-Shirt Shop

Raka sells T-shirts online. His shop has only two rules:

Here is the checkout function, written in a hurry. It calculates the total for one cart. The code runs and its result is right:

function calc(k, v) {
  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;
  if (t < 200) t = t + 15;
  return 'Total: $' + t.toFixed(2);
}

const cart = [
  { name: 'Plain Black Tee', price: 75, qty: 2 },
  { name: 'Coffee Print Tee', price: 95, qty: 1 },
];
console.log(calc(cart, 'SAVE10')); // Total: $220.50

Now imagine you are reading that function for the first time. Before you dare to change one line, you have to answer six questions:

  1. What is k? The shopping cart: a list of items, each with a price and a qty (quantity).
  2. What is v? The voucher code.
  3. What is t? The total, which the code keeps updating.
  4. What is 0.1? The 10% voucher discount.
  5. What limit is 200? The free-shipping minimum.
  6. What is 15? The shipping fee.

The answers to those six questions are only in the author's head. A number that appears in code with no explanation, like 0.1 and 200, is called a magic number.

The clean version

Here is the same function after tidying:

const VOUCHER_DISCOUNT = 0.1;  // SAVE10: 10% off
const FREE_SHIPPING_MIN = 200; // free shipping from $200
const SHIPPING_FEE = 15;

function calculateTotal(cart, voucherCode) {
  let total = 0;
  for (const item of cart) {
    total += item.price * item.qty;
  }
  if (voucherCode === 'SAVE10') total -= total * VOUCHER_DISCOUNT;
  if (total < FREE_SHIPPING_MIN) total += SHIPPING_FEE;
  return 'Total: $' + total.toFixed(2);
}

The logic hasn't changed at all: same steps in the same order, same numbers.

The computer doesn't care, people do

Both versions run on the same cart. Before you look at the output, guess: is the result the same, or is the clean version more accurate?

> calc(cart, 'SAVE10')
Total: $220.50
> calculateTotal(cart, 'SAVE10')
Total: $220.50

Exactly the same. Tidying code doesn't make its result more accurate. Only two things change: how fast a person understands the code, and how safely the code can be changed. The calculation: 2 × $75 + $95 = $245. Minus 10%, that is $220.50. $220.50 is above $200, so shipping is free. (toFixed(2) always writes two decimals, so the output says 220.50, not 220.5.)

Changing the shape of code without changing its result is called a refactor. This whole track is a series of small refactors of this checkout function.

Code is read far more often than it is written

The checkout function is written once. But it is read every time someone wants to add a voucher, change the shipping fee or look for a bug (a mistake in a program). In his book Clean Code (2008), Robert C. Martin put the ratio of time spent reading code to time spent writing it at "well over 10 to 1". That is an estimate from his experience, not a measurement. But it matches what many teams see. So most of the cost of maintaining code (maintenance) is the cost of reading it. Code that is easy to read lowers that cost.

Technical debt: a loan that charges interest

Technical debt is a term from Ward Cunningham (1992). Choosing a shortcut instead of the right solution works like taking a loan. You gain time now. Then you pay interest every time that code has to change. The interest is slower reading and mistakes that happen more easily.

An example: Raka asks for "free shipping from $250". In the clean version, you change one constant: FREE_SHIPPING_MIN = 250. In the messy version, you first have to make sure that 200 really is the free-shipping minimum. The more features are added to calc, the higher the interest.

A refactor that changes the result is a bug

Tidying is fine, changing the result is not. The cheapest way to make sure is a test: a little code that compares a function's result with what the result should be. Say someone "tidies" calculateTotal by moving the shipping check above the voucher check. The test below then runs on that changed version. The check function prints OK when the result matches what it should be, and DIFF when it does not:

function check(actual, expected) {
  console.log(actual === expected ? 'OK   ' + actual : 'DIFF ' + actual + ', expected ' + expected);
}

const cartD = [
  { name: 'Plain Black Tee', price: 75, qty: 1 },
  { name: 'Coffee Print Tee', price: 95, qty: 1 },
  { name: 'Raka Cap', price: 40, qty: 1 },
];
check(calculateTotal(cart, 'SAVE10'), 'Total: $220.50');
check(calculateTotal(cartD, 'SAVE10'), 'Total: $204.00');

The output:

OK   Total: $220.50
DIFF Total: $189.00, expected Total: $204.00

Cart D (cartD) adds up to $210. The right order: the voucher discount comes first and gives $189. $189 is below $200, so shipping is added and the total is $204. In the wrong version, shipping is checked first: $210 counts as free shipping, then 10% is taken off, which gives $189. The first cart gives the right result in both orders. So without cart D, nobody would notice this bug.

📌 Map of this track

This checkout function is tidied further in the next lessons. The lesson titles are in brackets:

The tiny check test is used at every step.

⚠️ What people get wrong about tidy code

TL;DR: Clean code is code that people can read easily and change safely. The computer doesn't care about names: the checkout function calc(k, v) and its clean version, calculateTotal(cart, voucherCode), both print Total: $220.50. Code is read far more often than it is written. So clear names lower the cost of maintaining code. So does giving a name to each magic number, which is a number that appears in code with no explanation. A shortcut that makes code hard to read is called technical debt: you pay interest on it, as slower reading, every time that code changes. A refactor changes the shape of code, not its result. A refactor that turns out to change the result can be caught by a tiny test. The test compares results before and after, using a shopping cart whose total is close to the limit in one of the shop's rules.

⚡ Names that make the reader guess

Write:

function calc(k, v) {
  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;
  if (t < 200) t = t + 15;
  return 'Total: $' + t.toFixed(2);
}
Guess first: this is the checkout function of a T-shirt shop. The code runs and its result is right. So what is 200?

The free-shipping minimum: when the total is below $200, the shipping fee 15 is added. That answer is only in the author's head. A number that appears in code with no explanation, like 0.1 and 200, is called a magic number.

Meaning: The computer doesn't care whether a variable is called k or cart. But a person who reads this code has to guess what k, v and t mean before daring to change a single line.

⚡ Give the numbers a name

Write:

const FREE_SHIPPING_MIN = 200; // free shipping from $200
const SHIPPING_FEE = 15;

if (total < FREE_SHIPPING_MIN) total += SHIPPING_FEE;

Meaning: This is the shipping check from the clean version, which is named calculateTotal. Two constants (fixed values with a name) give names to the magic numbers 200 and 15, and t becomes total. In that clean version, k also becomes cart and v becomes voucherCode. Those names answer the reader's questions. The logic hasn't changed at all.

⚡ The computer doesn't care, people do

Guess first: calc(cart, 'SAVE10') and its clean version, calculateTotal(cart, 'SAVE10'), run on the same cart. Is the clean version's result more accurate?

No. Both print Total: $220.50. Changing the shape of code without changing its result is called a refactor.

Meaning: The only things that change are how fast a person understands the code and how safely it can be changed. Code is read far more often than it is written. So code that is easy to read lowers the cost of maintaining it.

⚡ A tiny test catches a refactor that goes too far

Write:

check(calculateTotal(cart, 'SAVE10'), 'Total: $220.50');
check(calculateTotal(cartD, 'SAVE10'), 'Total: $204.00');

Meaning: check is a tiny test: it compares the result of calculateTotal with what the result should be, then prints OK when they are the same and DIFF when they are not. Say someone tidies the code and moves the shipping check above the voucher check. Cart D (cartD, an order of $210) then counts as free shipping, although after the 10% discount its total is below $200. check prints DIFF. The first cart (cart) gives the right result in both orders. So the test needs a cart whose total is close to the limit in a rule, here the free-shipping minimum.

What you will learn