Skip to content

Lesson 2 of 28Principles

Clean Code

Name things well, design signatures and errors that resist misuse, refactor safely with pinning tests, and let review and linters enforce it.

26 min read0/7 questions

You will read code about ten times more often than you write it. Clean code is code the next person (often you, in six months) can change without fear. It is also what reviewers judge in a take-home assignment long before they check whether your algorithm is optimal.

None of this is about taste. Every rule below exists because a specific kind of mess causes a specific kind of bug.

Names carry the design

A good name tells you what a thing is or does without reading its body. A bad name forces you to read the body, every time.

SmellBetterWhy
d, tmp, data2days_overdue, pending_refundsSays what it holds
process(), handle()charge_card(), send_receipt()Says what it does
flag, checkis_admin, has_expiredBooleans read as yes/no questions
user_list_dictusers_by_emailDescribes meaning, not the container
calc(a, b, True)calc_price(order, express=True)Call sites read like sentences

Length should match scope. A loop index i in a three-line loop is fine. A module-level constant called t is not.

Quick check
Which function name is best for code that returns the invoices a customer has not paid yet?
Need a nudge? A hint rules out a wrong answer.

Small functions, one level of abstraction

A function should read like a short story at one level of detail. If place_order mixes "charge the customer" with "strip whitespace from the postcode", the reader keeps switching zoom levels. Pull the low-level details into well-named helpers, and the top function becomes a table of contents.

One level per function
place_orderreads like a checklistrequire_itemsnormalise_addressvalidate_orderrulesapply_discountsadd_taxprice_ordermoneycharge_customerpayment gatewaysend_confirmationemailroot

The top function only calls four steps. You can read the whole business flow in five lines.

1/3

A useful test: can you describe what the function does without saying "and"? "Validates the order and charges the card and formats the email" is three functions.

Guard clauses beat deep nesting

Nested if blocks force you to hold every open condition in your head. A guard clause handles the special case first and returns early, so the main path runs flat at the left margin. Flag arguments (a boolean that switches the whole function into a different mode) are a related smell: two functions are hiding in one.

smell
def discount(user, total, is_sale):
    if user is not None:
        if user.active:
            if is_sale:
                return total * 0.8
            else:
                if total > 100:
                    return total * 0.9
                else:
                    return total
    return total
Python
from dataclasses import dataclass @dataclassclass User: active: bool def discount(user: User | None, total: float) -> float: if user is None or not user.active: return total if total > 100: return total * 0.9 return total def sale_discount(user: User | None, total: float) -> float: if user is None or not user.active: return total return total * 0.8 print(discount(User(active=True), 200))print(sale_discount(User(active=True), 200))print(discount(None, 200))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

def fee(amount, country):
  if amount <= 0:
      return 0
  if country == "US":
      return 2
  if amount > 1000:
      return 15
  return 5

print(fee(2000, "US") + fee(2000, "FR") + fee(-5, "FR"))
Need a nudge? Hints walk you through it.

Function signatures that resist misuse

A function's signature is the part every caller has to get right, so design it to make the wrong call hard to write. Four habits do most of the work.

Split flag arguments. You saw this with sale_discount. A boolean that changes what the function does means two functions share a name. The test is the call site: render(report, True) tells the reader nothing, render_preview(report) tells them everything.

Make options keyword-only. When a boolean or a setting genuinely tunes one behaviour, force callers to name it. In Python, every parameter after a bare * must be passed by keyword, and every parameter before a / must be passed by position (useful when the name is an implementation detail you may want to rename).

Python
def refund(order_id: str, /, amount_cents: int, *, notify: bool = True, reason: str = "requested") -> str: msg = f"refund {amount_cents} on {order_id} ({reason})" return msg + (" + email" if notify else "") print(refund("ord_1", 500))print(refund("ord_1", 500, notify=False, reason="damaged"))try: refund("ord_1", 500, False) # a bare boolean: what does it mean?except TypeError as e: print("TypeError:", e)
Output
Press Run (⌘ Enter) to see what happens.

The TypeScript equivalent is an options object: refund(orderId, amountCents, { notify: false, reason: "damaged" }). Destructure it with defaults in the signature ({ notify = true, reason = "requested" }: RefundOptions = {}) and callers can pass any subset in any order. Adding a new option later breaks no existing call.

Avoid output parameters. A function that fills in a list or dict you passed it (collect_errors(order, errors)) hides a write inside what looks like a read. Return the value instead: errors = validate(order). When a function must both change state and return something, say so in the name (pop_next_job()).

Never use a mutable default. Python evaluates default values once, when the def runs, not on each call. A default list is shared by every call that does not pass one.

Predict the outputPython

What does this print?

def add_tag(tag, tags=[]):
  tags.append(tag)
  return tags

a = add_tag("sale")
b = add_tag("new")
print(a, a is b)
Need a nudge? Hints walk you through it.

A rough limit worth keeping in mind: past three or four parameters, callers start passing them in the wrong order. That is the point to reach for keyword-only arguments, an options object, or the parameter object you will see below.

DRY, and the rule of three

DRY (don't repeat yourself) says each piece of knowledge should live in one place. The trap is merging code that only looks the same. Two validate functions that both check length today may serve different business rules tomorrow, and one shared helper then grows a pile of flags to serve both.

The rule of three: copy once, and on the third copy, extract. By then you can see what really varies. Duplication is cheaper than the wrong abstraction, because undoing a bad abstraction means untangling every caller.

Comments explain why

Code already says what it does. A comment that repeats it (# add one to i) is noise that goes stale. Good comments explain what the code cannot: the reason, the constraint, the trap.

# Bad: says what
retries += 1  # increment retries
 
# Good: says why
# Stripe returns 409 while a previous idempotent request is still in flight,
# so we retry instead of failing the checkout.
retries += 1

If you need a comment to explain what a block does, that is usually a hint to extract it into a function whose name says it.

Error handling is design

Error handling is where clean code matters most and gets the least attention. The happy path is usually fine. The bugs that page you at 3 a.m. are an exception swallowed in a try block, an error message that says invalid input, or a failure that surfaced three functions away from its cause.

Fail fast, at the boundary. Validate input where it enters your system (the request handler, the config loader, the queue consumer) and refuse bad data immediately. A config value that is wrong should crash the app at startup with a clear message, not after an hour when the first payment runs. Inside the core, code can then trust its inputs instead of re-checking them everywhere.

Write error messages for the person who will read them. A good message says what was wrong, shows the actual value, and if possible says what to do. Compare ValueError: invalid with the messages below.

Python
import json class ConfigError(Exception): pass def load_port(raw: str) -> int: try: cfg = json.loads(raw) except json.JSONDecodeError as e: raise ConfigError(f"config is not valid JSON (line {e.lineno}, column {e.colno})") from e port = cfg.get("port") if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: raise ConfigError( f"'port' must be an integer from 1 to 65535, got {port!r}. " "Set it in config.json, for example \"port\": 8080." ) return port for raw in ['{"port": 8080}', '{"port": "8080"}', '{"port": true}', '{"port": 8080,}']: try: print("ok:", load_port(raw)) except ConfigError as e: print("ConfigError:", e) print(" caused by:", type(e.__cause__).__name__ if e.__cause__ else None)
Output
Press Run (⌘ Enter) to see what happens.

Three details in that code are worth copying. The message includes the bad value with !r, so '8080' (a string) is visibly different from 8080. The bool check is there because in Python True is an int, so without it "port": true would quietly become port 1. And raise ... from e keeps the original exception attached as __cause__, so the traceback shows both the friendly message and the low-level JSONDecodeError with its position.

Never swallow. This is the most expensive line in many codebases:

try:
    sync_inventory()
except Exception:
    pass  # the job "succeeds" and nobody knows stock is wrong

If you catch an exception, do one of three things: handle it fully (retry, fall back to a default you can justify), translate it into an error that makes sense at this level and re-raise, or log it with the traceback (logger.exception(...)) and re-raise. Catch the narrowest type you can. A bare except Exception around twenty lines also catches the TypeError from your own typo.

Exceptions or return values? Use exceptions for things that should not happen in normal operation: the database is down, a file is corrupt, a bug. Use return values for expected outcomes the caller must deal with: a form field that fails validation, a coupon that has expired, a user who is not found. TypeScript makes this explicit with a result type, a union that the compiler forces you to check before you can reach the value:

TypeScript
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E }; type ParseError = { field: string; reason: string }; function parseQuantity(input: string): Result<number, ParseError> { const n = Number(input); if (!Number.isInteger(n)) return { ok: false, error: { field: "quantity", reason: `"${input}" is not a whole number` } }; if (n < 1 || n > 99) return { ok: false, error: { field: "quantity", reason: `must be 1 to 99, got ${n}` } }; return { ok: true, value: n };} for (const input of ["3", "2.5", "500"]) { const r = parseQuantity(input); console.log(r.ok ? `ok ${r.value}` : `invalid ${r.error.field}: ${r.error.reason}`);} // Unexpected failures still throw, and keep their cause.function loadPrices(raw: string): Record<string, number> { try { return JSON.parse(raw); } catch (err) { throw new Error("price list from the pricing service is not valid JSON", { cause: err }); }} try { loadPrices("{oops");} catch (e) { const err = e as Error; console.log(err.message); console.log("cause:", (err.cause as Error).name);}
Output
Press Run (⌘ Enter) to see what happens.

The cause option on Error (standard since ES2022) is the JavaScript version of raise ... from e. Use it every time you wrap an error, or the original stack is lost.

Quick check
A nightly job wraps its whole body in try: ... except Exception: logger.info('sync failed'). What is the best review comment?
Need a nudge? A hint rules out a wrong answer.

Smells and their refactorings

A code smell is a surface sign of a deeper design problem. A refactoring is a change to structure that keeps behaviour identical. Martin Fowler's catalogue names dozens; these are the ones you will use weekly.

This lesson keeps to the handful you will use every week. The Code Smells and Refactoring lesson goes through the wider catalogue and the techniques for changing legacy code safely.

SmellRefactoring
Long function doing several thingsExtract function
if type == ... repeated in many placesReplace conditional with polymorphism (a class or function per type)
Same 4 arguments passed together everywhereIntroduce parameter object (a dataclass or type)
Boolean flag argumentSplit into two functions
Magic number 0.2Named constant VAT_RATE
Deep nestingGuard clauses

Here is introduce parameter object in practice. Four loose values become one typed object, so call sites cannot swap two of them by accident:

Python
from dataclasses import dataclass # Before: quote(weight_kg, country, express, insured), easy to swap two booleans. @dataclass(frozen=True)class Shipment: weight_kg: float country: str express: bool = False insured: bool = False def quote(s: Shipment) -> float: base = 5 + 2 * s.weight_kg if s.express: base *= 2 if s.insured: base += 3 return base print(quote(Shipment(weight_kg=2, country="DE", insured=True)))
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/4 matched

Match each smell to the refactoring that fixes it.

Choose an item, then its match on the other side.

Refactoring safely

Refactoring without tests is just editing and hoping. Before you touch messy code, write tests that pin its current behaviour, including the weird cases. Then change structure in small steps and run the tests after each one.

Put it in order5 steps

Put a safe refactoring session in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Code review: where clean code is enforced

Most teams do not have a clean code document. They have code review, and review comments are how a team's standards actually spread. Being good at review, in both directions, is one of the clearest signals of a mid-level engineer.

Spend your comments on what tools cannot judge. In rough priority order:

  1. Correctness. Does it do what the ticket says? What happens with an empty list, a null, a retry, two requests at once?
  2. Design. Is this logic in the right layer? Will the next similar feature fit, or need a copy of this one?
  3. Names and readability. Could you understand this function from its name and signature alone?
  4. Tests. Do they pin the behaviour that matters, including the failure path?
  5. Style. Only if a linter cannot catch it. If you find yourself writing the same style comment twice, add a lint rule instead.

Label how much each comment matters. A reviewer's "why not a dict here?" can read as a blocking demand or as idle curiosity, and authors guess wrong. Conventional Comments is a small, widely used convention that fixes this by starting each comment with a label and an optional decoration:

issue (blocking): this catches Exception and returns [], so a DB outage
looks like "no orders". Can we let it raise and handle it in the route?
 
suggestion (non-blocking): `pending_refunds` would say more than `items` here.
 
question: is the 30s timeout from the vendor docs? A comment with the link would help.
 
nitpick: trailing `else` after `return` can go.
 
praise: the pinning tests around the old rounding bug are great.

The common labels are praise, nitpick, suggestion, issue, question, thought, todo and chore. The label tells the author what to do; the decoration (blocking, non-blocking, if-minor) tells them whether it must be fixed before merge.

As an author, make review easy: small pull requests (a few hundred lines is a common ceiling, beyond which reviewers start skimming), a description that says why, and self-review of your own diff before you ask anyone else. As a reviewer, comment on the code, not the person ("this function" rather than "you"), and approve with non-blocking suggestions instead of holding a pull request hostage to preferences.

Let tools enforce the boring parts

Every rule a machine can check should be checked by a machine, so humans spend review time on design and correctness. A modern setup has three layers.

  • A formatter decides layout so nobody argues about it: Ruff's formatter (Black-compatible) for Python, Prettier or Biome for TypeScript. Run it on save and in CI. Formatting comments in review should simply disappear.
  • A linter catches bug patterns and smells: unused variables, bare except, mutable defaults, missing await, unreachable code. Ruff covers most of what flake8, isort and pyupgrade used to do, in one fast tool. ESLint with typescript-eslint is the standard for TypeScript. Biome combines formatting and linting in one tool for JS and TS.
  • A type checker (mypy or pyright, tsc --noEmit with strict) catches the wrong-shape bugs that tests often miss.

Linters can also enforce the structural rules from this lesson. Cyclomatic complexity counts the independent paths through a function (roughly, one plus the number of if, loop, and/or and case branches). A limit around 10 is a common default, and a function that exceeds it is almost always one that needs guard clauses or extraction.

pyproject.toml
[tool.ruff.lint]
select = ["E", "F", "B", "I", "UP", "C90", "BLE"]  # B006: mutable defaults, BLE: blind except
 
[tool.ruff.lint.mccabe]
max-complexity = 10
eslint.config.js
import { defineConfig } from "eslint/config";
import js from "@eslint/js";
import tseslint from "typescript-eslint";
 
export default defineConfig([
  js.configs.recommended,
  tseslint.configs.recommended,
  {
    rules: {
      complexity: ["error", 10],
      "max-depth": ["error", 3],
      "max-params": ["error", 4],
    },
  },
]);

Rule names and preset contents change between versions, so check the Ruff and ESLint docs for your version before copying a config. Then wire it in at two points: a pre-commit hook (the pre-commit framework, or Husky with lint-staged for JS) so problems are fixed before they are pushed, and CI, so nothing merges without passing. On a legacy codebase, turn new rules on for changed files first, or the first run reports thousands of issues and the team switches it off.

Match the pairs0/4 matched

Match each problem to the cheapest place to catch it.

Choose an item, then its match on the other side.
ChallengeEasy

Refactor the shipping calculator

Here is a legacy shipping function. It works, but it is five levels deep and named ship(o).

def ship(o):
    if o is not None:
        if o["items"] > 0:
            if o["express"]:
                if o["country"] == "US":
                    return 25
                else:
                    return 60
            else:
                if o["total"] >= 100:
                    return 0
                else:
                    if o["country"] == "US":
                        return 8
                    else:
                        return 20
        else:
            return 0
    return 0

Rewrite it as shipping_cost(order) (TypeScript: shippingCost(order)) with guard clauses and named constants, keeping the behaviour exactly the same. The tests pin today's behaviour, including the odd parts:

  • no order (None / null) or zero items costs 0
  • express is 25 to the US and 60 elsewhere, and is never free
  • standard shipping is free when total >= 100, otherwise 8 to the US and 20 elsewhere

An order looks like {"items": 2, "total": 40, "country": "US", "express": false}.

def shipping_cost(order: dict | None) -> int: # Same behaviour as the legacy ship(o), but flat: handle the special # cases first with early returns. pass
Key terms
guard clause
An early return that handles a special case first so the main path stays flat.
code smell
A surface symptom (long function, flag argument, duplicated switch) that hints at a design problem.
refactoring
Changing the structure of code without changing what it does.
rule of three
Tolerate duplication twice; extract a shared abstraction on the third copy.
parameter object
A small type that groups values always passed together, replacing a long argument list.
pinning test
A test that records current behaviour before a refactor so any change in behaviour is caught.
fail fast
Rejecting invalid input or configuration at the boundary, immediately and loudly, instead of failing later and far away.
exception chaining
Attaching the original error when raising a new one (raise ... from e, new Error(msg, { cause })) so no context is lost.
result type
A return value that is either a success with a value or a failure with an error, which the caller must check.
keyword-only argument
A Python parameter after a bare * that callers must pass by name, so call sites stay readable.
cyclomatic complexity
A count of independent paths through a function; linters can fail a build when it passes a limit.
Conventional Comments
A review convention that starts each comment with a label (issue, suggestion, nitpick) and says whether it blocks merge.