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.

Beginner 5 min readLesson 3 of 9

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 ofPreferWhy
d, tmp, data2elapsedDays, pendingInvoicesReveal intent
getData()fetchUnpaidInvoices(customerId)Say what and from where
flag, checkisExpired, hasPermission, canRetryBooleans read as questions
processOrder() doing four thingsvalidateOrder, reserveStock, chargePaymentOne name, one job
int t; // timeout in secondsint timeoutSecondsUnits in the name
MgrImplHelperUtilA domain term: InvoiceSchedulerUse 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.
TypeScript
// 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.

Python
# ✗ 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 null for "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)

PrincipleMeansOverdone, it becomes
DRY — don't repeat yourselfEvery piece of knowledge has one authoritative placePremature abstraction coupling things that merely look alike. Duplication is cheaper than the wrong abstraction — wait for the "rule of three"
KISS — keep it simpleThe simplest solution that works— (rarely overdone)
YAGNI — you aren't gonna need itDon't build for imagined future requirementsIgnoring known, near-term needs
Single responsibilityOne reason to changeDozens of one-line classes
Law of DemeterTalk to friends, not strangers: avoid order.getCustomer().getAddress().getCity() chainsWrapper methods everywhere
Principle of least astonishmentCode 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:

SmellTypical refactoring
Long functionExtract function
Large class / god objectExtract class; split responsibilities
Long parameter listIntroduce a parameter object
Duplicated codeExtract a shared function (if it's the same knowledge)
Feature envy — a method uses another object's data more than its ownMove the method
Primitive obsession — strings and ints for emails, money, IDsIntroduce value types (Email, Money) with validation
Shotgun surgery — one change touches many filesConsolidate the scattered logic
Switch on type repeated in many placesPolymorphism or a lookup table (Strategy)
Magic numbersNamed constants
Dead code, speculative generalityDelete it
Deep nestingGuard 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 status enum 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).
Key takeaways
  • 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.