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.
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.
| Smell | Better | Why |
|---|---|---|
d, tmp, data2 | days_overdue, pending_refunds | Says what it holds |
process(), handle() | charge_card(), send_receipt() | Says what it does |
flag, check | is_admin, has_expired | Booleans read as yes/no questions |
user_list_dict | users_by_email | Describes 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.
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.
The top function only calls four steps. You can read the whole business flow in five lines.
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.
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 totalPress Run (⌘ Enter) to see what happens.function discount(user: User | null, total: number, isSale: boolean) {
if (user) {
if (user.active) {
if (isSale) return total * 0.8;
else {
if (total > 100) return total * 0.9;
else return total;
}
}
}
return total;
}Press Run (⌘ Enter) to see what happens.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"))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).
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.
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)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 += 1If 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.
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 wrongIf 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:
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.
try: ... except Exception: logger.info('sync failed'). What is the best review comment?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.
| Smell | Refactoring |
|---|---|
| Long function doing several things | Extract function |
if type == ... repeated in many places | Replace conditional with polymorphism (a class or function per type) |
| Same 4 arguments passed together everywhere | Introduce parameter object (a dataclass or type) |
| Boolean flag argument | Split into two functions |
Magic number 0.2 | Named constant VAT_RATE |
| Deep nesting | Guard 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:
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Match each smell to the refactoring that fixes it.
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 a safe refactoring session in order.
- Tap the steps below in the right order.
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:
- Correctness. Does it do what the ticket says? What happens with an empty list, a null, a retry, two requests at once?
- Design. Is this logic in the right layer? Will the next similar feature fit, or need a copy of this one?
- Names and readability. Could you understand this function from its name and signature alone?
- Tests. Do they pin the behaviour that matters, including the failure path?
- 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, missingawait, 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 --noEmitwithstrict) 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.
[tool.ruff.lint]
select = ["E", "F", "B", "I", "UP", "C90", "BLE"] # B006: mutable defaults, BLE: blind except
[tool.ruff.lint.mccabe]
max-complexity = 10import { 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 each problem to the cheapest place to catch it.
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 0Rewrite 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 costs0 - express is
25to the US and60elsewhere, and is never free - standard shipping is free when
total >= 100, otherwise8to the US and20elsewhere
An order looks like {"items": 2, "total": 40, "country": "US", "express": false}.
- 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.