Self-Documenting Code: What It Can and Can't Explain

Raghav Chamadiya8 min read
On this page

Self-documenting code is code written so that its names, types and structure explain what it does without a comment. It is a real and worthwhile goal, and it has a hard ceiling: it answers "what" and sometimes "how", and it never answers "why".

That ceiling is the point. A function called charge_with_retry tells you what it does. It cannot tell you that the team tried a queue first and dropped it, or why the retry count is 3. That reasoning is not in any identifier, however good.

If you came for a style guide, the naming advice below stands on its own. The rule of thumb: write code that needs no comment to explain what it does, then put the reasons somewhere a person can find them.

What is self-documenting code?

Self-documenting code is code whose identifiers, function boundaries and types carry enough meaning that a competent reader follows it without prose beside it. The idea is most associated with Robert Martin's Clean Code, which treats a comment that explains what code does as a sign the code failed to express its intent. For the wider discipline, see clean code.

The idea is right about one thing: a comment that restates the code is noise, and it rots. i += 1 # increment i costs a line and tells you nothing.

The mistake is stretching it into "good code needs no comments at all". That sentence mixes up two different questions.

The three questions code can be asked

Every reader of a piece of code asks some mix of three things.

QuestionCan code answer it?Where the answer lives
What does this do?Yes, with good names and typesThe code itself
How does it do it?Often, with small functions and clear flowThe code, sometimes a short comment
Why is it this way?NoCommits, decision records, comments, docs

Scroll the table sideways to see every column.

"What" and "how" are properties of the code as it stands today. "Why" is a fact about the past: what was known, what was tried, what was rejected and who needed what. A snapshot of the code has no memory of any of that.

A before and after: what good naming buys you

Here is code that makes a reader work for everything.

python
def proc(d, f):
    r = []
    for x in d:
        if x[2] > 30 and not x[5]:
            r.append(x)
    if f:
        r.sort(key=lambda x: x[2])
    return r

Every part of that is a guess. What is d? What is column 2? Why 30? Rename and restructure, and most of the guessing goes away.

python
from dataclasses import dataclass

OVERDUE_GRACE_DAYS = 30

@dataclass
class Invoice:
    id: str
    customer_id: str
    days_overdue: int
    is_disputed: bool

def overdue_invoices(invoices: list[Invoice], sort_by_age: bool = False) -> list[Invoice]:
    overdue = [
        inv for inv in invoices
        if inv.days_overdue > OVERDUE_GRACE_DAYS and not inv.is_disputed
    ]
    if sort_by_age:
        overdue.sort(key=lambda inv: inv.days_overdue)
    return overdue

Now the function name says what it returns, the type says what goes in, the field names replace the column indexes, and OVERDUE_GRACE_DAYS turns a magic number into a named one. A new reader gets the what and the how in ten seconds. That is a real win, and it cost no comments.

Look at what is still missing. Why is a disputed invoice excluded? Why a grace period, and why that length? Was a per-customer grace period considered? You cannot recover any of it from the code, and no renaming will put it there.

What types buy you

Types are the strongest self-documentation tool most languages give you, because the checker keeps them honest and a comment never is.

python
# Before: the reader has to guess what the strings mean
def schedule(job_id: str, run_at: str, retries: int) -> bool: ...

# After: the signature states the contract
from datetime import datetime
from typing import Literal, NewType

JobId = NewType("JobId", str)
JobStatus = Literal["queued", "rejected"]

def schedule(job_id: JobId, run_at: datetime, max_retries: int) -> JobStatus: ...

The second signature says that run_at is a point in time, that the result is one of two named states, and that a job id is not any old string. A wrong call fails in the editor. A comment saying the same thing would be correct on the day it was written and nothing after.

Types cover what, and they cover it well. They still say nothing about why max_retries is bounded where it is.

Where self-documenting code runs out

Three kinds of knowledge are never in the code.

The decision. Code shows the option that won. It does not show that there was a choice. Two engineers reading a polling loop cannot tell whether polling was picked on purpose or because nobody got to webhooks.

The rejected alternative. The most expensive thing a team forgets is what it already tried. Without a record, the next person proposes the same idea, spends a week on it and hits the same wall.

Cross-file intent. A rule often spans files: this field must be written in the API layer because the billing job reads it three modules away. No identifier in either file mentions the other. A function name describes one function, and intent about how the system hangs together has no home in it.

Here is the same overdue_invoices module with the knowledge that is missing. The reasons are an invented example, there to show the shape of a good comment.

python
# Disputed invoices are excluded on purpose: finance chases those by hand,
# and automated reminders on a disputed amount made customers angry.
# A per-customer grace period was considered and dropped; one global value
# keeps the reminder job's query simple.
OVERDUE_GRACE_DAYS = 30

That comment is not restating the code. It holds facts that exist nowhere else in the file, and it will still be true next year even if the code around it changes. That is the test for a good comment.

Where comments still earn their place

Comments are not the opposite of clean code. A comment is worth its line when it says something the code cannot.

  • A non-obvious reason. Why this value, why this order, why this odd-looking guard.
  • A workaround. The bug in a dependency, the version it was fixed in, the condition to delete the workaround.
  • A trap. Something that looks safe to change and is not: "do not reorder, the second call depends on the first call's side effect".
  • A rejected alternative. One line is enough: "not using a queue here, see the decision record".

What does not earn a place: restating the next line, describing a function whose name already describes it, and anything that has to be edited every time the code is. If a comment answers "what", try a better name first. If it answers "why", keep it.

Keep them short and attach them to the exact line they explain. A paragraph at the top of a file about the whole module will be wrong inside a year, because nobody edits it when the code changes. For more on structuring all of this, see code documentation.

Where the why should live

A comment next to a line is the right home for a reason that stays true as long as that line exists. Bigger reasons need a bigger home.

What you need to recordWhere it belongs
Why this change was madeThe commit message, written as a reason and not a list of edits
Why the team chose this design over anotherA decision record (ADR) with context, options considered and consequences
Why this line looks strangeA short comment on that line
How a module fits into the systemPer-module documentation next to the code
A rule that spans several filesA decision record that names the files it governs

Scroll the table sideways to see every column.

The commit message is the most underused of these. It is attached to the exact change, it is versioned with the code, and git blame takes you straight to it. A message like "Fix invoice bug" wastes that. "Exclude disputed invoices from reminders: automated emails on disputed amounts upset customers" is documentation that costs nothing extra.

For choices that outlive one change, write a decision record. We cover the format and why it works in architectural decision records and capturing the why, and where to keep the files in where architecture decisions live.

Self-documenting code and AI agents

A coding agent reads your code the way a new hire does: all of it, with no memory of the meeting where a choice was made. Good names help it as much as they help a person. They do not tell it that a pattern was deliberately chosen over the obvious one, so it "simplifies" the odd-looking code and removes the thing that was protecting you.

That makes recorded reasons more valuable, not less. An agent that is told "this file is governed by a decision to avoid per-customer grace periods" does not need to guess. History also shows things no identifier can, such as files that always change together or code nobody dares touch, as covered in code smells.

How repowise keeps the why findable

The reasoning behind your code mostly exists already. It is scattered across commit messages, pull request descriptions, ADR files and # WHY: comments, and nobody can find it when they need it.

repowise reads those sources and turns them into decision records: a title, the decision, the context, the rationale, the rejected alternatives and the files it governs (see decisions and docs/layers/DECISIONS.md in the open source repo). An agent editing a governed file is told about the decision in one line, so the reason arrives at the moment someone is about to undo it. repowise also keeps a wiki page for each source file and module, regenerated for the files a commit touched, so "how does this part fit in" has an answer that stays close to the code (see the wiki).

Names and types stay your job. The why is the part you should not have to keep in your head.

A short checklist

  • Rename until a comment explaining what the code does would be redundant.
  • Replace magic numbers and stringly-typed arguments with named constants and types.
  • Keep functions small enough that the name covers the whole body.
  • Write commit messages as reasons.
  • Record any choice with a rejected alternative as a decision.
  • Comment the line that looks wrong and is right.

More on the standards around this lives in coding standards, and the whole topic sits under code quality.

FAQ

What is self-documenting code?
Self-documenting code is code written so that its names, types and structure make clear what it does without needing comments. The goal is for a competent reader to follow the intent from the identifiers and function boundaries alone.
Does self-documenting code mean no comments?
No. Self-documenting code removes comments that restate what the code does. It does not remove comments that explain why: a non-obvious reason, a workaround, a trap or a rejected alternative. Those are not in any identifier, so they still need to be written down.
How do you write self-documenting code?
Use names that state intent, keep functions small and single-purpose, replace magic numbers with named constants, and use types to carry meaning (a datetime instead of a string, a literal union instead of free text). Then check each remaining comment: if it explains what, improve the name instead.
Why is self-documenting code not enough?
Code records the outcome of a decision, never the decision. It cannot show what alternatives were rejected, what constraint forced the choice, or how a rule connects several files. That context has to live in commit messages, decision records or comments.
Where should the "why" behind code live?
Put reasons at the narrowest level that stays true. A short comment for a strange line, a commit message for a change, a decision record for a design choice, and per-module docs for how a part fits the system.
What is a self-documenting identifier?
A self-documenting identifier is a name that states its purpose well enough that no comment is needed, such as days_overdue instead of d or is_disputed instead of flag. It tells the reader what a value is or what a function returns. It cannot tell them why the value is what it is.