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.
| Rule | Bad | Good |
|---|---|---|
| Say what it is or does | d, data, temp, x | daysUntilExpiry, unpaidInvoices |
| Functions are verbs | invoice() | createInvoice(), calculateVat() |
| Booleans read as yes/no questions | flag, status | isActive, hasPaid, canEdit |
| Avoid unclear abbreviations | custRegDt | customerRegisteredAt |
| Include units | timeout = 30 | timeoutSeconds = 30, pricePence |
| One word per concept | fetchUser, getOrder, retrieveInvoice | Pick one verb (get...) and use it everywhere |
| Match the business language | doThing2() | 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:
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:
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 ior 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
| Habit | Why |
|---|---|
| No magic numbers | if (age >= 18) → const ADULT_AGE = 18; * 0.2 → VAT_RATE |
| Handle errors explicitly | No empty catch {}; fail with a clear message; never swallow errors silently (Lesson 263) |
| Few parameters | More than three or four: pass an object with named fields |
| Avoid boolean flag parameters | render(true) is unreadable; use two functions or an options object { showHeader: true } |
| Immutability by default | const, readonly types, returning new values (Lesson 48) reduce surprise changes |
| Consistency | Follow the codebase's conventions; use a formatter (Prettier) and a linter (ESLint) so style is never debated in reviews |
| Delete dead code | Unused functions and flags confuse readers |
| The Boy Scout rule | Leave 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
| Word | Meaning |
|---|---|
| Clean code | Code that is easy to read and safe to change |
| Guard clause | An early return for special cases |
| Magic number | An unexplained literal value in code |
| Refactoring | Improving structure without changing behaviour |
| Linter / formatter | Tools enforcing code rules / layout |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.