Agent Wranglers

ARC-19Recommended

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. Choose each name as Name things for what they mean says.

Examples

JavaScript 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;

Python example

# 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

JavaScript example 2

// 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;
}

JavaScript example 3

// 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];

JavaScript example 4

// 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. The same build runs the function length limit from Keep functions short and the vague-name ban from Name things for what they mean.

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/architecture/comments/self-documenting-code">Agent Wranglers clean code and architecture playbook</a>. In code you write, add a comment next to it with the same link.