Self-Documenting Code
If it looks like a hedgehog and acts like a hedgehog, it MUST be a hedgehog.
If the comment is doing the explaining, then the code isn't. Make the shape of the code tell the story so the comment becomes redundant.
Opinion
Copy a note and link
Grab this short comment and drop it into a PR comment or an LLM chat to prompt the right change.
Don't add a comment that explains what the code does: make the code itself clear instead. If the meaning isn't obvious, rename the function, split it, or improve the names of its parameters. Comments are for explaining *why* something works the way it does, not *what* it does. /tenet/self-documenting-code/F5
AI eyes only
Rule: meaning lives in the code. A comment that explains what code does is a defect.
Reject: comments that paraphrase the next line. Reject: JSDoc / docstring that restates parameter names or types the type system already declares. Reject: “this function does X” preambles.
Generate: better names. If a comment is genuinely needed, it explains why, a constraint, an external bug, a non-obvious invariant: never what.
Diagnostic: delete the comment. If the code now reads ambiguously, rename or split the function until it does not. Re-add only when the comment is the sole place a non-obvious why lives.
Why?
- Makes developers and AI agents honour F1 Single Responsibility Principle.
- Faster to write: naming the function honestly per F2 Intention-Revealing Names is faster than naming it dishonestly and then explaining the gap.
- Comments rot. The code changes. The comment beside it doesn't. By the third commit the prose lies about the line above it. The next reader either trusts the comment and merges a bug, or distrusts every comment they meet. Cutting the comment cuts the rot at source.
- Removes bloat. Every comment is a line a reviewer must read, an LLM must spend tokens on and a future editor must keep aligned. Strip the prose. Let the names do the explaining.
- Coding agents weight code more than comments. When the comment and the code disagree, the agent follows the code: the comment becomes dead text the model still pays tokens to read.
- Cuts review time, names and shape do the explaining instead of prose.
- Removes a class of merge conflicts (the kind where the comment lies about the new code).
Origins
The rule is older than most of the developers reading it. Brian Kernighan and P. J. Plauger's The Elements of Programming Style (1974) sets it down in a single line: “Don't comment bad code — rewrite it.”6 Decades before Clean Code, the discipline was already in print: the comment is the symptom, the rewrite is the cure.
Robert C. Martin's Clean Code (2008) argued the position again, in chapter four, with no patience left for the steelman: comments are almost always a sign of failure. The code could not say it itself, so a human had to step in and translate.1 Martin allows good comments (legal headers, public-API explainers, intent the language cannot express) but they are vastly outnumbered by the bad ones. The bad ones do active harm by drifting out of sync with the code they purport to describe.
The position is best understood by reading it against its steelman opposite, written a generation earlier. Donald Knuth's 1984 essay Literate Programming proposed the inverse discipline: write the prose first, in narrative order, and let the source code fall out of it like footnotes from a paragraph.2 Knuth's target was the typeset document rather than the editor pane. The difference in production model explains most of the disagreement. When the artefact is a printed paper, the comment is the artefact. When the artefact is a feature shipped at speed by half-a-dozen authors and an LLM, the comment is debt.
Martin Fowler later catalogued the position in Refactoring, 2nd edition (2018), listing “Comments” among the bad smells: an explanatory comment is usually a symptom that the name is wrong or the function is doing too much.3 Fix the code beneath it and the smell goes with it.
Quotes
Indeed, I have often suggested that every comment represents a failure to make the code self explanatory.
Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.
When you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous.
Evidence
20 external sources, ranked by author authority. The first five are the canon; expand to see the rest, including the qualifiers and the named opposers. Each links out to its primary source.
- 01Clean Code, ch. 4 “Comments”SupportsThe most-cited source for the principle. Comments are a failure of expression. Refactor the code rather than annotating it.
- 02“Necessary Comments”QualifiesMartin steel-manning the exception: reaffirms comments-as-failure but admits a narrow class: involved algorithms, timing diagrams.
- 03Three chapters defend comments. Argues “self-documenting code” is wrong: rationale, units, edge cases and interface contracts can’t live in code alone.
- 04Comments should explain why (purpose, intent, constraints) and never what. The what should live in the code itself.
- 05Formalised the term. Treats programming style as documentation, since the code often becomes the only documentation that survives.
- 06“Coding Without Comments”SupportsTreat comments as last-resort. Refactor first, name better, and only then comment. “Write your code as if comments didn’t exist.”
- 07“When Good Comments Go Bad”SupportsComments rot as code drifts. The best comments are the ones you didn’t need to write.
- 08Argues self-documenting code is impossible. The writer brings invisible context the reader lacks. Comments encode classes of information names alone cannot.
- 09Direct refutation of the “comment only the why” formulation. Argues the what often needs commenting too.
- 10“Why Not Comments”QualifiesNames the unique value of negative-information comments, recording what was not done and why, which can’t be encoded in identifiers.
- 11The most-quoted single-sentence formulation. Coined the standard distinction: code does not say (refactor) vs code cannot say (comment).
- 12Encodes self-documenting code as the “Rule of Clarity”. Programs are written for the maintainer first, the machine second.
- 13Middle-ground: comments are good but should never explain how. If you need a comment to explain how, rewrite the code instead.
- 14The philosophical anti-thesis: programs as documents written for humans, with code embedded in prose. The strongest historical case for prose inside the program.
- 15Self-documentation through the type system rather than naming. Useful breadth: not all advocates of the principle are naming-only.
- 16Naming is the lever for self-documentation. The problem is not difficulty but tolerance of bad names.
- 17“Get better at naming things”SupportsNaming is a design activity, not labelling. Self-documentation is design work.
- 18“Comments”: code-smell entrySupportsComments classified as a Dispensable smell. Prescription: rename, extract function, then delete the comment.
- 19The canonical counter-essay. Opposes not the principle itself but its dogmatic application: over-extraction, side-effects, poor names.
- 20Modern synthesis of the canonical compromise. Code shows how, comments record why. Cites Atwood directly.
Twenty sources, three stances. The supports cluster on the Martin canon, qualified by McConnell and the Pragmatic Programmer line between explaining the what and the why. The opposing voice is Ousterhout: rationale, edge cases and interface contracts cannot live in code alone. The honest argument is between the qualifiers and the opposers, not between the supporters and the sceptics.
Examples
// How many spines does the hedgehog have function handle(patchCm2: number, pricklesPerCm2: number): number { // number of spines = body area times the number of spines per square cm const scratch = patchCm2 * pricklesPerCm2; // return the number of spines return scratch; }
function countHedgehogSpines(bodyAreaCm2: number, spinesPerCm2: number): number { return bodyAreaCm2 * spinesPerCm2; }
// How many spines does the hedgehog have function handle(patchCm2: number, pricklesPerCm2: number): number { // number of spines = body area times the number of spines per square cm const scratch = patchCm2 * pricklesPerCm2; // return the number of spines return scratch; }
function countHedgehogSpines(bodyAreaCm2: number, spinesPerCm2: number): number { return bodyAreaCm2 * spinesPerCm2; }
// How many spines does the hedgehog have function handle(patchCm2, pricklesPerCm2) { // number of spines = body area times the number of spines per square cm const scratch = patchCm2 * pricklesPerCm2; // return the number of spines return scratch; }
function countHedgehogSpines(bodyAreaCm2, spinesPerCm2) { return bodyAreaCm2 * spinesPerCm2; }
# How many spines does the hedgehog have def handle(patch_cm2: int, prickles_per_cm2: int) -> int: # number of spines = body area times the number of spines per square cm scratch = patch_cm2 * prickles_per_cm2 # return the number of spines return scratch
def count_hedgehog_spines(body_area_cm2: int, spines_per_cm2: int) -> int: return body_area_cm2 * spines_per_cm2
// How many spines does the hedgehog have public int handle(int patchCm2, int pricklesPerCm2) { // number of spines = body area times the number of spines per square cm int scratch = patchCm2 * pricklesPerCm2; // return the number of spines return scratch; }
public int countHedgehogSpines(int bodyAreaCm2, int spinesPerCm2) { return bodyAreaCm2 * spinesPerCm2; }
// How many spines does the hedgehog have function handle(int $patchCm2, int $pricklesPerCm2): int { // number of spines = body area times the number of spines per square cm $scratch = $patchCm2 * $pricklesPerCm2; // return the number of spines return $scratch; }
function countHedgehogSpines(int $bodyAreaCm2, int $spinesPerCm2): int { return $bodyAreaCm2 * $spinesPerCm2; }
Enforcement
Apply these rules in eslint.config.mjs. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| prickles/no-comments | the pack's eslint.config.mjs | every comment, JSDoc included. Only tool directives pass: eslint-disable and eslint-enable, @ts-expect-error with its description, prettier-ignore, triple-slash references and the #! line. SPDX licence lines and generated-file banners (@generated, or Code generated … DO NOT EDIT) pass too, as F5 holds that they are metadata, not comments. |
| @typescript-eslint/ban-ts-comment | typescript-eslint | @ts-ignore and @ts-nocheck, and @ts-expect-error without a description. |
| no-inline-comments | ESLint core | any comment on the same line as code. |
| no-warning-comments | ESLint core | TODO / FIXME / XXX / HACK markers, named on their own. |
| sonarjs/no-commented-code | eslint-plugin-sonarjs | commented-out code, named on its own. |
eslint.config.mjsconfiguration snippet
import { defineConfig } from 'eslint/config';
import tseslint from 'typescript-eslint';
const allowed = [
/^[\s*]*(?:eslint-(?:disable|enable)|@ts-expect-error|prettier-ignore|@generated|SPDX-(?:License-Identifier|FileCopyrightText):)/u,
/^[\s*]*(?:Code generated|Generated by)\b.*\bDO NOT EDIT\b/u,
/^\/\s*<reference\s/u,
];
const prickles = {
rules: {
'no-comments': {
meta: { schema: false, messages: { comment: 'Remove the comment.' } },
create: (context) => ({
Program() {
for (const comment of context.sourceCode.getAllComments()) {
const isAllowed = allowed.some((pattern) => pattern.test(comment.value));
if (comment.type !== 'Shebang' && !isAllowed) {
context.report({ loc: comment.loc, messageId: 'comment' });
}
}
},
}),
},
},
};
export default defineConfig({
files: ['**/*.{ts,tsx}'],
extends: [tseslint.configs.base],
plugins: { prickles },
rules: {
'prickles/no-comments': 'error',
'@typescript-eslint/ban-ts-comment': 'error',
'no-inline-comments': 'error',
'no-warning-comments': ['error', { terms: ['todo', 'fixme', 'xxx', 'hack'] }],
},
});Apply these rules in eslint.config.mjs. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| prickles/no-comments | the pack's eslint.config.mjs | every comment, JSDoc included. Only tool directives pass: eslint-disable and eslint-enable, @ts-expect-error with its description, prettier-ignore, triple-slash references and the #! line. SPDX licence lines and generated-file banners (@generated, or Code generated … DO NOT EDIT) pass too, as F5 holds that they are metadata, not comments. |
| @typescript-eslint/ban-ts-comment | typescript-eslint | @ts-ignore and @ts-nocheck, and @ts-expect-error without a description. |
| no-inline-comments | ESLint core | any comment on the same line as code. |
| no-warning-comments | ESLint core | TODO / FIXME / XXX / HACK markers, named on their own. |
| sonarjs/no-commented-code | eslint-plugin-sonarjs | commented-out code, named on its own. |
eslint.config.mjsconfiguration snippet
import { defineConfig } from 'eslint/config';
import tseslint from 'typescript-eslint';
const allowed = [
/^[\s*]*(?:eslint-(?:disable|enable)|@ts-expect-error|prettier-ignore|@generated|SPDX-(?:License-Identifier|FileCopyrightText):)/u,
/^[\s*]*(?:Code generated|Generated by)\b.*\bDO NOT EDIT\b/u,
/^\/\s*<reference\s/u,
];
const prickles = {
rules: {
'no-comments': {
meta: { schema: false, messages: { comment: 'Remove the comment.' } },
create: (context) => ({
Program() {
for (const comment of context.sourceCode.getAllComments()) {
const isAllowed = allowed.some((pattern) => pattern.test(comment.value));
if (comment.type !== 'Shebang' && !isAllowed) {
context.report({ loc: comment.loc, messageId: 'comment' });
}
}
},
}),
},
},
};
export default defineConfig({
files: ['**/*.{ts,tsx}'],
extends: [tseslint.configs.base],
plugins: { prickles },
rules: {
'prickles/no-comments': 'error',
'@typescript-eslint/ban-ts-comment': 'error',
'no-inline-comments': 'error',
'no-warning-comments': ['error', { terms: ['todo', 'fixme', 'xxx', 'hack'] }],
},
});Apply these rules in eslint.config.mjs. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| prickles/no-comments | the pack's eslint.config.mjs | every comment. Only tool directives pass: eslint-disable and eslint-enable, prettier-ignore and the #! line. SPDX licence lines and generated-file banners (@generated, or Code generated … DO NOT EDIT) pass too, as F5 holds that they are metadata, not comments. The pack also lets through JSDoc blocks of type tags alone while allowTypeDocBlocks is on. |
| no-inline-comments | ESLint core | any comment on the same line as code. |
| no-warning-comments | ESLint core | TODO / FIXME / XXX / HACK markers, named on their own. |
| eslint-comments/require-description | eslint-plugin-eslint-comments | eslint-disable without a reason after it. |
| sonarjs/no-commented-code | eslint-plugin-sonarjs | commented-out code, named on its own. |
eslint.config.mjsconfiguration snippet
import js from '@eslint/js';
import eslintComments from '@eslint-community/eslint-plugin-eslint-comments/configs';
const allowed = [
/^[\s*]*(?:eslint-(?:disable|enable)|@ts-expect-error|prettier-ignore|@generated|SPDX-(?:License-Identifier|FileCopyrightText):)/u,
/^[\s*]*(?:Code generated|Generated by)\b.*\bDO NOT EDIT\b/u,
/^\/\s*<reference\s/u,
];
const prickles = {
rules: {
'no-comments': {
meta: { schema: false, messages: { comment: 'Remove the comment.' } },
create: (context) => ({
Program() {
for (const comment of context.sourceCode.getAllComments()) {
const isAllowed = allowed.some((pattern) => pattern.test(comment.value));
if (comment.type !== 'Shebang' && !isAllowed) {
context.report({ loc: comment.loc, messageId: 'comment' });
}
}
},
}),
},
},
};
export default [
js.configs.recommended,
eslintComments.recommended,
{
files: ['**/*.{js,mjs,cjs}'],
plugins: { prickles },
rules: {
'prickles/no-comments': 'error',
'no-inline-comments': 'error',
'no-warning-comments': ['error', { terms: ['todo', 'fixme', 'xxx', 'hack'] }],
'@eslint-community/eslint-comments/require-description': ['error', { ignore: [] }],
},
},
];Apply these rules in pyproject.toml. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| C9601 / C9602 (prickles-comment, prickles-docstring) | Pylint, with the pack's prickles_no_comments.py | every # comment and every docstring, since a docstring is a comment too. Only tool directives pass: # type: ignore, # noqa, # pylint: disable or enable, and the #! line. SPDX licence lines and generated-file banners (@generated, or Code generated … DO NOT EDIT) pass too, as F5 holds that they are metadata, not comments. |
| ERA001 | Ruff (eradicate) | commented-out Python code, named on its own. |
| FIX001-FIX004 | Ruff (flake8-fixme) | FIXME / XXX / HACK / TODO markers, named on their own. |
pyproject.tomlconfiguration snippet
[tool.ruff.lint]
select = [
"ERA", # eradicate: commented-out code
"FIX", # flake8-fixme: TODO/FIXME/HACK/XXX markers
]
[tool.pylint.MAIN]
init-hook = "import sys; sys.path.insert(0, '')"
load-plugins = ["prickles_no_comments"]
[tool.pylint."MESSAGES CONTROL"]
disable = [
"missing-module-docstring",
"missing-class-docstring",
"missing-function-docstring",
]Apply these rules in pmd-ruleset.xml. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| CommentContent | PMD | every comment, Javadoc included, through a forbiddenRegex that matches any text but the tool directives // NOPMD and CHECKSTYLE:OFF or CHECKSTYLE:ON. SPDX licence lines and generated-file banners (@generated, or Code generated … DO NOT EDIT) pass too, as F5 holds that they are metadata, not comments. |
| CommentSize | PMD | comments longer than N lines or M chars per line, named on their own. |
| TodoComment | Checkstyle | TODO / FIXME markers (regex-configurable). |
| S125 (commented-out code) | SonarQube Java | sections of code that have been commented out. |
| S1135 (TODO tags) | SonarQube Java | TODO markers in committed code. |
pmd-ruleset.xmlconfiguration snippet
<?xml version="1.0"?>
<ruleset name="prickles-self-documenting" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0">
<description>Every comment fails but // NOPMD, the CHECKSTYLE toggles, SPDX lines and generated banners.</description>
<rule ref="category/java/documentation.xml/CommentContent">
<properties>
<property name="forbiddenRegex" value="^(?!\s*((NOPMD|CHECKSTYLE:(OFF|ON)|@generated)\b|SPDX-(License-Identifier|FileCopyrightText):|(Code generated|Generated by)\b.*\bDO NOT EDIT\b)).*\S"/>
</properties>
</rule>
<rule ref="category/java/documentation.xml/CommentSize"/>
</ruleset>Apply these rules in phpcs.xml. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| Prickles.Commenting.NoComments | PHP_CodeSniffer, with the pack's NoCommentsSniff.php | every //, # and /* */ comment and every docblock. Only tool directives pass: phpcs:ignore, phpcs:disable and phpcs:enable, @phpstan-ignore, @psalm-suppress and PHPMD's @SuppressWarnings. SPDX licence lines and generated-file banners (@generated, or Code generated … DO NOT EDIT) pass too, as F5 holds that they are metadata, not comments. Docblocks of type tags alone, which Psalm and PHPStan read, pass while allowTypeDocBlocks is on. |
| Generic.Commenting.Todo | PHP_CodeSniffer | TODO / FIXME markers, named on their own. |
phpcs.xmlconfiguration snippet
<?xml version="1.0"?>
<ruleset name="prickles-self-documenting">
<file>src</file>
<rule ref="./phpcs/Prickles/Sniffs/Commenting/NoCommentsSniff.php">
<properties>
<property name="allowTypeDocBlocks" value="true"/>
</properties>
</rule>
<rule ref="Generic.Commenting.Todo"/>
</ruleset>AI rules
.cursor/rules/f5-self-documenting-code.mdc--- alwaysApply: true --- ## Prickles F5: Self-Documenting Code Do not add comments that explain what the code does. If a reader needs help, improve names, extract functions, add types, or add tests until the code tells the story. Do not use a comment as a substitute for refactoring. If you are about to comment, refactor first. Allowed without debate: SPDX license headers, autogenerated file banners, and narrow linter suppressions that match your repo's required shape (e.g. eslint-disable-next-line with rule id). Refuse to "just add a comment" instead of fixing unclear code.
Repo layout, CI, and ESLint wiring for these paths live on /implementation, not repeated on every tenet.
Counter-argument
The honest steelman is Knuth's, sharpened by a modern librarian's instinct. There is a class of code (public-API surface, cryptographic primitives, numerical routines) whose contract is what the caller must understand. That contract is irreducibly prose. No name holds the bit-level guarantees of a hashing function. No signature explains why a particular sort is stable. Knuth's literate-programming case2 is that for these artefacts the prose is the deliverable, not decoration. Hillel Wayne extends the point to the why-not-what comment: the line of code can be obvious and still need a sentence saying this exists because the vendor's clock skews on leap seconds.4
Counter-argument retort
On reflection, neither concession holds. The strongest cases the research can muster all reduce.
Knuth's literate-programming case2 was written for typeset documents whose deliverable was a printed paper. Modern cryptographic primitives are published as self-documenting code. The proof is a separate paper on arXiv, peer-reviewed, with its own citation. Two artefacts, not one.
Hillel Wayne's negative-information case4 (recording what was not done and why) looks irreducible at first. A regression test whose name is the rationale ( “does not double-validate merchantId since the upstream webhook is authoritative” ) plus an ADR for the architectural decision does the same job with a stronger audit trail; neither artefact rots silently the way a comment does.
Ousterhout's rationale-and-edge-cases case5 is mostly types waiting to be written. See T1 Domain-Driven Types. A Result<T, E> makes every error path explicit. A Branded<string, “UserId”> removes the ambiguity the comment was patching. Where types cannot hold the constraint, a property-based test usually can.
The genuine residue is not what the canon means by “comment”: SPDX-License-Identifier headers, AUTO-GENERATED markers that tooling depends on, ESLint-disable directives that already come with a justification. These are metadata interfaces between the source and external systems, not explanation aimed at a human reader. Police their format with a linter. Do not call them comments.
In production code the comment that explains is the code that lies. The next reader trusts the comment over the code. The comment is wrong. A bug goes out. Refactor: name the function, type the parameter, write the test, file the ADR, publish the doc. The discipline is irreducible. The comment is not.
Notes
- [1]Robert C. Martin: Clean Code (Prentice Hall, 2008), ch. 4 “Comments”: “The proper use of comments is to compensate for our failure to express ourselves in code.”
- [2]Donald E. Knuth: “Literate Programming”, The Computer Journal 27 (2), 1984. The steelman case for prose alongside code, written for typeset documents: a different production model than the modern editor and reviewer.
- [3]Martin Fowler: Refactoring, 2nd ed. (Addison-Wesley, 2018). Lists Comments under Bad Smells in Code: “a comment is often used as a deodorant”.
- [4]Hillel Wayne: “Why Not Comments” (buttondown.com/hillelwayne, 2024). Argues the rule needs an exception for negative-information comments: recording what was not done and why.
- [5]John Ousterhout: A Philosophy of Software Design (2018, 2021). The strongest steelman for explanatory comments: defends rationale, units, edge cases and interface contracts as belonging in prose. The reply argues each of those reduces to types, tests or ADRs.
- [6]Brian W. Kernighan & P. J. Plauger: The Elements of Programming Style (McGraw-Hill, 1974; 2nd ed. 1978), “Summary of Rules”: “Don’t comment bad code — rewrite it.” The earliest published statement of the principle, more than three decades before Clean Code put it in front of a generation of working developers.