Small, Focused Functions — Clean Code

Measure a function by how many things it does, not by its length. Describe what it does in one sentence: every "and" is one more thing. The 9-line checkout…

The fried rice you made is too salty. If the recipe is split into named steps (fry the paste, add the rice, season, serve), you only check the "season" step. You don't need to read the recipe again from the start. On the menu, all those steps are still a single line: fried rice.

Functions work the same way. Each step of the recipe is a small function with a name, and the "fried rice" line on the menu is the function that calls those steps. A good function does one thing. The measure isn't its number of lines, but whether you can tell what the function does in one sentence without the word "and".

One sentence without "and"

Here is the checkout function of Raka's T-Shirt Shop after its names were tidied in the previous lesson:

const VOUCHER_DISCOUNT = 0.1;
const FREE_SHIPPING_MIN = 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 calculateTotal function is only 9 lines long. Before you read on, guess: how many things does it do? One, two, or four?

Describe what it does in one sentence: calculateTotal adds up the item prices, and takes off the voucher, and adds shipping, and turns the result into a price in dollars. Three "and"s, so four things: only 9 lines, but four jobs. The measure isn't the function's length, but how many things the function does itself.

Split it step by step

Each step moves into its own function with a verb for a name:

function calculateSubtotal(cart) {
  let subtotal = 0;
  for (const item of cart) {
    subtotal += item.price * item.qty;
  }
  return subtotal;
}

function applyVoucher(amount, voucherCode) {
  if (voucherCode === 'SAVE10') return amount - amount * VOUCHER_DISCOUNT;
  return amount;
}

function addShipping(amount) {
  if (amount < FREE_SHIPPING_MIN) return amount + SHIPPING_FEE;
  return amount;
}

function formatPrice(amount) {
  return '$' + amount.toFixed(2);
}

function calculateTotal(cart, voucherCode) {
  let total = calculateSubtotal(cart);
  total = applyVoucher(total, voucherCode);
  total = addShipping(total);
  return 'Total: ' + formatPrice(total);
}

Split without changing the order

Splitting a function is a refactor: the shape of the code changes, but the result has to stay the same. Run the tests with the four carts in the first lesson's Lab, before and after splitting:

Cart Voucher Result that must stay
A: 2 plain tees + 1 printed tee ($245) SAVE10 Total: $220.50
A none Total: $245.00
C: 1 plain tee ($75) none Total: $90.00
D: 1 plain tee + 1 printed tee + 1 cap ($210) SAVE10 Total: $204.00

Say two lines in calculateTotal get swapped while splitting. Shipping is then checked before the voucher discount:

total = addShipping(total);               // swapped
total = applyVoucher(total, voucherCode);

The tiny check test from the first lesson prints this:

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

Three carts still print OK. Only cart D catches the mistake, because its total is close to the free-shipping minimum. The good news: once the function is split, the order of the steps is easy to see, because the voucher discount and shipping are on two lines next to each other.

A function that puts steps together also does one thing

calculateTotal is now a function that puts steps together: it only calls four steps. It still does one thing, which is calculating the total, because all four steps belong to the same task. The function below is different:

function processOrder(order) {
  validateOrder(order);
  calculateTotal(order);
  sendConfirmationEmail(order);
  updateInventory(order);
  generateInvoice(order);
}

It passes all its work to other functions. But processOrder ties together five concerns from different areas: the order, the price, email, warehouse stock and documents (the invoice). Every time one of them changes its conditions or its order (for example, the email should be sent only after the payment is complete), this function changes too. So it still does too much. It is more focused when it is split by concern. For example, one function handles only the order until it is saved, and other functions handle the email, stock and invoice after that.

The exercise: a student grade report

In the exercise, the function processStudents also does three things at once: it keeps the students who passed, calculates the average, and builds the report. Split it into:

  1. filterPassingStudents(students): returns the students with grade >= 70.
  2. calculateAverage(students): returns the average grade. For an empty list, it returns 0.
  3. formatReport(passing, average): returns the text Passed: X students, Average: Y, with X the number of students in passing.

processStudents then only calls all three in order. Of the five students, Budi 85, Citra 92 and Eka 78 pass. Their average is (85 + 92 + 78) / 3 = 85, so the output stays Passed: 3 students, Average: 85.

Why check for an empty list? For an empty list, the sum of the grades is 0 and the number of students is 0, so the division is 0 / 0. In JavaScript 0 / 0 is NaN (Not a Number), not 0. Write if (students.length === 0) return 0; before dividing.

⚠️ Already split, still a problem?

TL;DR: Measure a function by how many things it does, not by its length. Describe what it does in one sentence: every "and" is one more thing. The 9-line checkout function calculateTotal turns out to do four things. So it's split into calculateSubtotal, applyVoucher, addShipping and formatPrice, and calculateTotal only puts them together (it calls all four in order). Each small function can be tested on its own. Splitting is a refactor (the shape changes, the result stays): the order must stay, and the four shopping carts used in the test must give the same results as before. Cart D (Total: $204.00), whose total is close to the free-shipping minimum, catches a swapped order. A function that puts steps together is fine as long as its steps belong to one task. A processOrder that ties together five different concerns still does too much. In the exercise: a student passes with a grade >= 70, the average of an empty list is 0 (not NaN, the result of 0 / 0), and the report reads Passed: 3 students, Average: 85.

⚡ One sentence without "and"

Guess first: the checkout function calculateTotal is only 9 lines long. How many things does it do?

Four. It adds up the item prices, and takes off the voucher, and adds shipping, and turns the result into a price in dollars. Three "and"s, so four things.

Meaning: A good function does one thing. The measure isn't its number of lines, but whether you can tell what the function does in one sentence without the word "and".

⚡ Split it step by step

Write:

function calculateTotal(cart, voucherCode) {
  let total = calculateSubtotal(cart);
  total = applyVoucher(total, voucherCode);
  total = addShipping(total);
  return 'Total: ' + formatPrice(total);
}

Meaning: Each step now has its own function. calculateTotal only puts the steps together: it calls the four functions in order, and its four lines read like a table of contents. Each step can be tested on its own: applyVoucher(210, 'SAVE10') gives 189.

⚡ The order must stay

Write:

total = addShipping(total);               // swapped
total = applyVoucher(total, voucherCode);
Guess first: these two lines got swapped while splitting, so shipping is checked before the voucher discount. The test runs on four shopping carts. How many carts catch the mistake?

Just one, cart D (an order of $210, close to the free-shipping minimum of $200): DIFF Total: $189.00, expected Total: $204.00. The other three still print OK.

Meaning: Splitting a function is a refactor: the shape of the code changes, but the result must stay the same. Run the tests before and after splitting, with a cart whose total is close to the limit in a rule.

⚡ The average of an empty list

Write:

if (students.length === 0) return 0;

Meaning: In the exercise, calculateAverage(students) calculates the average grade of the students. For an empty list, the division is 0 / 0, and in JavaScript that is NaN (Not a Number), not 0. This line returns 0 before dividing, because in the exercise calculateAverage of an empty list must return 0.

What you will learn