Raka's T-Shirt Shop has two copies of the instructions for its cash register. One is taped to the machine, so it gets replaced when the machine is replaced. The other is kept in the office drawer. The copy in the drawer still describes the old machine, and nobody notices until a new employee follows it.
Documentation as code picks the first way: documentation is treated like code. The copy taped to the machine is documentation kept together with its code, and the copy in the drawer is a document kept somewhere else. Documentation is written as plain text (Markdown, a text format with simple marks, such as # for a heading) in the same repo. It is changed in the same commit and pull request as the code, reviewed together, and where possible checked by a machine.
The checkout's README
The README is the file people read first in a repo, like its front door. It says what this is, how to run it, the rules that matter, and an example. Raka's checkout has a README.md in the same folder as checkout.js:
# Raka's T-Shirt Shop Checkout
Works out the order total: subtotal, voucher discount, then shipping.
## Rules
- The voucher SAVE10 takes 10% off.
- Shipping is $15, free when the total after the discount is at least $200.
## Examples
calculateTotal(cartA, 'SAVE10') // Total: $220.50
calculateTotal(cartC, '') // Total: $90.00
Because it is a Markdown file in the repo, a change to the README appears in the pull request's diff, just like code. A document in Word, Google Drive or a separate wiki (a site of notes that a team edits together) is not in that diff, so no reviewer asks for it.
Stale documentation throws no error
Raka wants free shipping from $250. You change FREE_SHIPPING_MIN = 250 and the expected results in the tests. The code now gives:
> calculateTotal(cartA, 'SAVE10')
Total: $235.50
After the SAVE10 discount, cart A comes to $220.50. That is now below $250, so shipping is charged. The tests pass, because the expected results in the tests were changed too. But the README still says Total: $220.50 and at least $200. Nothing tells you. The README is just text, and nothing runs it. Wrong documentation is worse than none, because people trust it and follow it.
Examples that run
The README's examples are written in a pattern a machine can read: the function call, then // and the expected result. This small script runs every example exactly as written:
const carts = { cartA, cartC, cartD };
function checkExamples(doc) {
const pattern = /calculateTotal\((\w+), '(\w*)'\);?\s*\/\/ (.+)/g;
for (const [, cartName, voucherCode, expected] of doc.matchAll(pattern)) {
check(calculateTotal(carts[cartName], voucherCode), expected);
}
}
checkExamples(README); // README: the contents of README.md as a string
DIFF Total: $235.50, expected Total: $220.50
OK Total: $90.00
patternis a regular expression (regex), a pattern for searching text. Each part inside round brackets captures one piece of text: the cart's name, the voucher code, and the text after//.matchAllfinds every example indocthat fits the pattern. The comma at the start of[, cartName, voucherCode, expected]skips the full text of the example, so the three names after it get the three pieces.carts[cartName]gets the cart from its name in the README. Thencheckfrom the first lesson compares the result with the expected text.- Run the script with the tests on every commit, and a stale README fails the way a test fails.
Real tools have the same idea: cargo test in Rust runs the examples in doc comments, and Python has the doctest module. But the machine only checks the examples. The sentence "at least $200" still has to be changed by a person, and the reviewer asks for it in the same pull request.
JSDoc for calculateTotal
JSDoc is a /** ... */ comment right above a function. It explains how to call the function. Inside it are tags (markers) that start with @. Editors such as VS Code show the JSDoc when you move the mouse pointer over the function's name:
/**
* Works out the order total: subtotal, voucher discount, then shipping.
* @param {Array} cart The items in the cart, each with a price and qty.
* @param {string} voucherCode The voucher code, '' when there is none.
* @returns {string} The total text for the receipt.
* @example
* calculateTotal(cartA, 'SAVE10'); // Total: $220.50
*/
function calculateTotal(cart, voucherCode) { /* ... */ }
@param {type} name description: one line per parameter.@returns {type}: what the function gives back.@example: a usage example, in the same pattern as the README's examples, socheckExamplescan run it too.
Write JSDoc for functions other people call. A small function that is used only inside its own module (the code file where it is written), and whose name is already clear, needs no JSDoc.
ADR: recording why
An ADR (Architecture Decision Record) is one short Markdown file for each important decision about how the code is arranged, kept in docs/adr/. The format comes from Michael Nygard ("Documenting Architecture Decisions", 2011): title, status, context, decision, consequences. Here is one, for the decision to use the voucher table from the Refactoring Techniques lesson:
# ADR-0002: Vouchers are kept in a VOUCHERS table
Status: accepted
## Context
Every new voucher adds an if to applyVoucher, and PR #14 (SAVE20) changed a function that was already tested.
## Decision
Voucher rates are kept in a VOUCHERS table; applyVoucher reads VOUCHERS[voucherCode] when Object.hasOwn(VOUCHERS, voucherCode), otherwise 0.
## Consequences
A new percentage voucher takes one line. A voucher that isn't a percentage, such as $25 off, doesn't fit a rate table and needs a new decision.
Its status is one of proposed, accepted, deprecated (no longer used) or superseded (replaced by a newer ADR). An ADR isn't edited once accepted. If the decision changes, write a new ADR that replaces it. A year from now, whoever asks "why a table, not a class?" finds the answer in the repo.
Every kind of documentation has a job
- Names say what:
calculateTotal,FREE_SHIPPING_MIN(the Good Naming lesson). - Comments say the why the code can't show, as in the Code Comments lesson. For example,
// Poll every 5 seconds because the client's office firewall blocks WebSocket. Polling means asking the server again every few seconds, a WebSocket is a connection that stays open, and a firewall is a network filter. The comment stops someone from "fixing" the code by switching to WebSocket. - JSDoc: how to call a public function (a function other people call). README: how to run it and the rules that matter. ADR: why a big decision was made.
Exercise: parseJsDoc and validateAdr
In the exercise, parseJsDoc(comment) turns JSDoc text into data. The pattern /@param\s*\{(\w+)\}\s*(\w+)([^@]*)/g is used again and again with exec in a while. Each time exec finds one @param, group 1 (the first part in round brackets) holds the type, group 2 the name, and group 3 the description up to the next @. /@returns?\s*\{(\w+)\}/ takes the return type. When there is no @returns, returns stays null, never made up. For '/** @param {string} name User name @param {number} age @returns {boolean} */' you get 2 params. The first is named name and has the type string, and the return type is boolean.
validateAdr(adr) pushes one error for each required field that is empty (title, status, context, decision, consequences), and one more when status isn't one of the four statuses above. valid is errors.length === 0, so it is true only when there are no errors. A complete ADR gives true and 0. { title: 'Test', status: 'unknown' } gets 4 errors (three empty fields, one status), so it gives false, and errors.length >= 2 is true. The output is eight lines, one per console.log in the editor:
2
name
string
boolean
true
0
false
true
⚠️ Why do docs go stale without anyone noticing?
- Documents outside the repo. A wiki or Drive isn't in the pull request's diff, so nobody asks for it when the code changes.
- Examples nobody runs. The README says
$220.50, the code gives$235.50, and nothing fails. Run the examples with the tests. - Thinking the example check catches everything. "At least $200" in a sentence still has to be changed by a person, and the reviewer asks for it in the same PR.
- An ADR written months later. By then the context and the alternatives are forgotten. Write it when you decide, and add a new ADR when the decision changes.
- In the exercise, making up
returns. Without@returns, the result isnull, not{ type: undefined }.
TL;DR: Documentation as code: docs are written as Markdown (plain text with simple marks) in the same repo as the code. They are changed in the same pull request, reviewed with the code, and their examples are run by a machine. The README, the file people read first in a repo, holds what it is, how to run it, the rules and an example. Stale documentation throws no error. After the free-shipping minimum becomes $250, a README that still says Total: $220.50 is only caught if its examples run (checkExamples prints DIFF Total: $235.50). JSDoc, a /** ... */ comment above a function (@param {type} name, @returns, @example), explains how to call a public function. An ADR records the context, decision and consequences of an architecture decision (a big decision about how the code is arranged), with status proposed, accepted, deprecated (no longer used) or superseded (replaced). Comments say why. In the exercise: parseJsDoc returns params { name, type, description }, and returns is null when there is no @returns. validateAdr pushes an error for every empty field and for an invalid status, and the output is 2, name, string, boolean, true, 0, false, true.
⚡ Docs in the same repo
Meaning: Documentation as code: docs are written as Markdown (plain text with simple marks) in the same repo as the code. They are changed in the same pull request and reviewed with the code. A document in Word, Drive or a separate wiki isn't in the diff, so no reviewer asks for it.
⚡ Stale docs throw no error
Guess first: the README (the instructions file in the repo) gives Total: $220.50 as the result for cart A with SAVE10. Then the free-shipping minimum rises to $250, and the code and tests are updated, but the README is not. What tells you?
Nothing. The README is just text and nothing runs it, while the code now gives Total: $235.50.
Meaning: Wrong documentation is worse than none, because people trust it and follow it.
⚡ Examples that run
Write:
for (const [, cartName, voucherCode, expected] of doc.matchAll(pattern)) {
check(calculateTotal(carts[cartName], voucherCode), expected);
}
Meaning: This script runs every example in doc (the README's text) exactly as written. pattern is a text-search pattern (a regex) that takes the cart's name, the voucher code and the expected result from each example. carts[cartName] gets the cart from its name, then check compares the result with the expected one. Run it with the tests on every commit, and a stale README fails too: DIFF Total: $235.50.
⚡ JSDoc and ADR
Write:
/**
* @param {string} voucherCode The voucher code, '' when there is none.
* @returns {string} The total text for the receipt.
*/
Meaning: JSDoc is a /** ... */ comment above a public function (a function other people call). It explains how to call the function: @param for each parameter, @returns for what it gives back. An ADR (Architecture Decision Record) is a short file that records why a big decision was made (context, decision, consequences), with status proposed, accepted, deprecated (no longer used) or superseded (replaced).