Clean Code
Writing code people can read and change — meaningful names, small focused functions, comments that explain why, error handling, DRY/KISS/YAGNI, cohesion and coupling, code smells and refactoring, immutability, and the trade-offs behind the rules.
Code is read far more often than it's written — by teammates, reviewers, and you in six months. Clean code is code whose intent is obvious and that's cheap and safe to change. It's not about beauty; it's about the cost of the next change. (For design-level principles — SOLID, patterns and anti-patterns — see SOLID and Anti-patterns and clean code.)
Names
Good names are the cheapest documentation.
| Instead of | Prefer | Why |
|---|---|---|
d, tmp, data2 | elapsedDays, pendingInvoices | Reveal intent |
getData() | fetchUnpaidInvoices(customerId) | Say what and from where |
flag, check | isExpired, hasPermission, canRetry | Booleans read as questions |
processOrder() doing four things | validateOrder, reserveStock, chargePayment | One name, one job |
int t; // timeout in seconds | int timeoutSeconds | Units in the name |
MgrImplHelperUtil | A domain term: InvoiceScheduler | Use the business's vocabulary (ubiquitous language) |
Name length should match scope: i is fine in a three-line loop; a module-level constant deserves a full name. Avoid misleading names (userList that's a set) and near-duplicates (accountData vs accountInfo).
Functions
- Do one thing, at one level of abstraction. If you can describe a function only with "and", split it.
- Keep them small enough to read at a glance — a guideline, not a law.
- Few parameters: more than three suggests a missing type. Avoid boolean flag parameters (
render(true)) — they hide two functions in one. - No hidden side effects:
checkPassword()shouldn't also start a session. - Command–query separation: a function either changes state or returns information, not both.
- Prefer early returns (guard clauses) over deep nesting.
// Before: nested, mixed levels of abstraction
function ship(order: Order) {
if (order) {
if (order.items.length > 0) {
if (order.paid) {
for (const item of order.items) {
db.query(`UPDATE stock SET qty = qty - ${item.qty} WHERE sku = '${item.sku}'`);
}
mailer.send(order.email, "Shipped!", "…");
} else throw new Error("unpaid");
}
}
}
// After: guard clauses, intention-revealing helpers, one level of abstraction
function ship(order: Order): void {
if (order.items.length === 0) return;
if (!order.paid) throw new UnpaidOrderError(order.id);
inventory.release(order.items);
notifications.orderShipped(order);
}(The "after" version also fixes a SQL injection — readable code makes bugs easier to see — Web security.)
Comments
Code says what and how; comments should say why.
# ✗ Restates the code
i += 1 # increment i
# ✓ Explains a non-obvious decision
# Retry only once: the payment provider charges twice if a retried request
# arrives after the original succeeded (their idempotency keys expire in 60s).
MAX_PAYMENT_RETRIES = 1- Good comments: intent, trade-offs, warnings, links to tickets or specs, explanations of workarounds, public API documentation.
- Bad comments: noise, outdated descriptions (worse than none), commented-out code (that's what version control is for), comments compensating for bad names — rename instead.
Error handling
- Fail loudly and early on programmer errors; handle expected failures explicitly.
- Don't swallow exceptions (
catch (e) {}) — at least log with context, or let them propagate. - Use specific error types and messages that help the next person: what failed, with which input, and what to do.
- Don't return
nullfor "not found" when the language offers better (Optional,Result, nullable types checked by the compiler — Rust error handling). - Separate the happy path from error handling so the main logic stays readable.
- Validate at boundaries (user input, external APIs); trust internal invariants.
Principles (and their limits)
| Principle | Means | Overdone, it becomes |
|---|---|---|
| DRY — don't repeat yourself | Every piece of knowledge has one authoritative place | Premature abstraction coupling things that merely look alike. Duplication is cheaper than the wrong abstraction — wait for the "rule of three" |
| KISS — keep it simple | The simplest solution that works | — (rarely overdone) |
| YAGNI — you aren't gonna need it | Don't build for imagined future requirements | Ignoring known, near-term needs |
| Single responsibility | One reason to change | Dozens of one-line classes |
| Law of Demeter | Talk to friends, not strangers: avoid order.getCustomer().getAddress().getCity() chains | Wrapper methods everywhere |
| Principle of least astonishment | Code behaves as its name and context suggest | — |
Cohesion and coupling
- High cohesion: things that change together live together (a module about invoices contains invoice logic, not email formatting).
- Low coupling: modules depend on few, stable, narrow interfaces of each other — so a change in one rarely forces changes in others.
Organise code by feature/domain (orders/, billing/) rather than only by technical layer (controllers/, models/) for large codebases — it keeps related code together.
Code smells
Symptoms that suggest (not prove) a design problem:
| Smell | Typical refactoring |
|---|---|
| Long function | Extract function |
| Large class / god object | Extract class; split responsibilities |
| Long parameter list | Introduce a parameter object |
| Duplicated code | Extract a shared function (if it's the same knowledge) |
| Feature envy — a method uses another object's data more than its own | Move the method |
| Primitive obsession — strings and ints for emails, money, IDs | Introduce value types (Email, Money) with validation |
| Shotgun surgery — one change touches many files | Consolidate the scattered logic |
| Switch on type repeated in many places | Polymorphism or a lookup table (Strategy) |
| Magic numbers | Named constants |
| Dead code, speculative generality | Delete it |
| Deep nesting | Guard clauses, extract function |
Refactoring
Refactoring is changing the structure of code without changing its behaviour, in small, safe steps, each verified by tests.
- Have tests first — they're the safety net (Testing).
- Make one small change at a time (rename, extract, move, inline) and run tests after each; IDE automated refactorings make many of these safe.
- Don't mix refactoring and behaviour changes in one commit — reviewers can't tell which caused what.
- Follow the boy scout rule: leave code a little cleaner than you found it, in the area you're already changing.
- For large legacy code: add characterisation tests capturing current behaviour, then use the strangler fig approach — gradually route functionality to new code.
Other habits
- Immutability by default (
const,final, frozen dataclasses, records) removes whole classes of bugs. - Make illegal states unrepresentable with types: a
statusenum instead of three booleans that can contradict each other. - Consistent formatting via automatic tools (Prettier, Black, gofmt, rustfmt) — never argue about style in reviews.
- Linters and static analysis in CI.
- Small, focused commits and pull requests (Code review).
- Clean code minimises the cost and risk of the next change; it's read far more than written.
- Names reveal intent and units; functions do one thing at one level of abstraction with few parameters and guard clauses.
- Comments explain why, not what; delete commented-out code and fix bad names instead of commenting them.
- Handle errors explicitly with context; validate at boundaries.
- Apply DRY, KISS and YAGNI with judgement — duplication beats the wrong abstraction.
- Aim for high cohesion and low coupling; recognise smells; refactor in small, tested, separate steps.