Skip to the content

Lesson 266 of 296

Clean code

What you will learn

  • Why readability matters more than cleverness
  • Naming
  • Small functions with one job
  • Guard clauses and avoiding deep nesting
  • Comments: when and how
  • Magic values, error handling and consistency
  • A refactoring example
On this page

Why clean code?

Code is read far more often than it is written: by teammates, reviewers, and you in six months. Clean code is code that is easy to understand and safe to change. Clever one-liners that nobody can follow are a cost, not a skill.

Naming

Good names remove the need for most comments.

RuleBadGood
Say what it is or doesd, data, temp, xdaysUntilExpiry, unpaidInvoices
Functions are verbsinvoice()createInvoice(), calculateVat()
Booleans read as yes/no questionsflag, statusisActive, hasPaid, canEdit
Avoid unclear abbreviationscustRegDtcustomerRegisteredAt
Include unitstimeout = 30timeoutSeconds = 30, pricePence
One word per conceptfetchUser, getOrder, retrieveInvoicePick one verb (get...) and use it everywhere
Match the business languagedoThing2()issueRefund(), the term the business uses

Small functions with one job

A function should do one thing at one level of detail. If you need "and" to describe it ("validates the order and charges the card and sends the email"), split it. Small functions are easier to name, test and reuse.

Guard clauses instead of deep nesting

Deeply nested if blocks are hard to follow. Return early for the special cases, and keep the main path flat.

Before:

TypeScript
type Order = { status: "draft" | "paid" | "cancelled"; items: { pricePence: number; quantity: number }[]; couponPercent?: number };

export function orderTotalNested(order: Order | null): number {
  let total = 0;
  if (order) {
    if (order.status !== "cancelled") {
      if (order.items.length > 0) {
        for (const item of order.items) {
          total += item.pricePence * item.quantity;
        }
        if (order.couponPercent) {
          total = total - Math.round((total * order.couponPercent) / 100);
        }
      }
    }
  }
  return total;
}

After:

TypeScript
const subtotal = (items: Order["items"]) => items.reduce((sum, item) => sum + item.pricePence * item.quantity, 0);

const applyCoupon = (amountPence: number, percent = 0) => amountPence - Math.round((amountPence * percent) / 100);

export function orderTotal(order: Order | null): number {
  if (!order || order.status === "cancelled") return 0;
  return applyCoupon(subtotal(order.items), order.couponPercent);
}

Same behaviour (checked by comparing both versions on 2,000 random orders), but each piece has a name and a single job, and the main logic reads like a sentence.

Comments

  • Good code explains what and how through names and structure. Comments should explain why: business rules, surprising decisions, links to tickets or regulations.
  • Bad: // increment i or comments that repeat the code. Worse: outdated comments that contradict the code.
  • Do not leave commented-out code; Git remembers it.
  • Public APIs and libraries benefit from doc comments (/** ... */, JSDoc/TSDoc).
// HMRC requires VAT to be rounded per invoice line, not on the total (see VAT Notice 700).
const lineVat = Math.round(lineNet * VAT_RATE);

Other habits

HabitWhy
No magic numbersif (age >= 18) → const ADULT_AGE = 18; * 0.2 → VAT_RATE
Handle errors explicitlyNo empty catch {}; fail with a clear message; never swallow errors silently (Lesson 263)
Few parametersMore than three or four: pass an object with named fields
Avoid boolean flag parametersrender(true) is unreadable; use two functions or an options object { showHeader: true }
Immutability by defaultconst, readonly types, returning new values (Lesson 48) reduce surprise changes
ConsistencyFollow the codebase's conventions; use a formatter (Prettier) and a linter (ESLint) so style is never debated in reviews
Delete dead codeUnused functions and flags confuse readers
The Boy Scout ruleLeave code a little cleaner than you found it, in small safe steps

Refactoring

Refactoring means improving the structure of code without changing its behaviour. Do it in small steps, with tests protecting you (Lesson 271). Common refactorings: rename, extract function, extract variable, inline, replace conditional with polymorphism (Lesson 269), introduce parameter object. IDEs automate many of them safely.

How to say it in an interview

"I optimise for readability because code is read far more than written. I use names that reveal intent and units, keep functions small with one responsibility, return early with guard clauses instead of nesting, replace magic numbers with named constants, and write comments that explain why rather than what. I never swallow errors, keep parameters few, follow the team's formatter and linter, and refactor in small behaviour-preserving steps protected by tests."

Key words

WordMeaning
Clean codeCode that is easy to read and safe to change
Guard clauseAn early return for special cases
Magic numberAn unexplained literal value in code
RefactoringImproving structure without changing behaviour
Linter / formatterTools enforcing code rules / layout

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.