Comments Recommended
Let the code explain itself
Name things so the code explains itself, and write a comment only for a reason the code cannot show.
How to do it
Give each function a name that says what it does or returns, such as isCacheFresh or renderPageHead. Name values for what they hold, not their type. Turn magic numbers into named constants. Split a long function into named steps instead of adding comments between parts. Keep a comment only for a decision the code cannot show, such as a browser bug or a measured trade-off. Delete every comment that repeats the code. If an agent or a new developer needs a comment to follow a function, rename it or split it.
Example
// Before: the comment carries the meaning the names don't
// check if the cached copy is less than 5 minutes old
const f = h => Date.now() - Date.parse(h.headers.get('date')) < 300000;
// After: the names say it, so no comment is needed
const FIVE_MINUTES = 5 * 60 * 1000;
const isCacheFresh = response => Date.now() - Date.parse(response.headers.get('date')) < FIVE_MINUTES;
# Before: the comment carries the meaning the names don't
def f(h):
return time.time() - h.date < 300 # less than 5 minutes old
# After: the names say it
FIVE_MINUTES = 5 * 60
def is_cache_fresh(response):
return time.time() - response.date < FIVE_MINUTES
// Before: comments mark the steps of one long function
function build(page) {
// add the metadata
// inline the stylesheet
// check the page
}
// After: each step is a function whose name is the comment
function buildPage(page) {
const html = inlineStylesheet(addMetadata(page));
assertPageRules(html);
return html;
}
// A comment that earns its place: it explains a reason, not the code.
// Chrome holds first paint until preloaded fonts arrive (measured: 80 ms later), so fonts are not preloaded.
const preloads = [heroImage];
// The check: fail when comments pass 10% of the code
const lines = source.split('\n').filter(line => line.trim());
const commentLines = lines.filter(line => /^\s*(\/\/|\/\*|\*)/.test(line)).length;
const share = commentLines / lines.length;
if (share > 0.1) {
console.log(`FAIL ${file}: ${Math.round(share * 100)}% comments (max 10%)`);
process.exit(1);
}
How to check
A script fails when comment lines pass 10% of a file's code. For names and function length, add a linter, such as ESLint for JavaScript, Pylint or Ruff for Python, or PHPMD for PHP.
For agents: if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in Based on the Agent Wranglers architecture playbook: https://agentwranglers.se/playbook/architecture/comments/self-documenting-code.