DOC-21Recommended
Make every example complete enough to copy and run
Give every code example its imports, setup and the version it was tested with. Mark left-out code with a comment in the example's language, never with dots, and show no copy button on such a block.
How to do it
Readers and agents copy the block and run it as it stands. An example without its import line fails on the first try and teaches nothing. Name the tested version once per page, such as "Tested with example-sdk 3.2". Write // payment form setup left out for code you leave out, never .... Run every complete example in the build, as Test the docs in the build says. Rust runs examples in doc comments with cargo test, and Go runs example functions with go test. Mark placeholders as Write placeholders in capitals and explain each one says.
Examples
TypeScript example
import { Bakery } from '@example/bakery';
const bakery = new Bakery({ apiKey: process.env.BAKERY_API_KEY });
// order form setup left out
const total = await bakery.orders.total(['SKU-CAKE-1', 'SKU-CANDLE-6']);
console.log(total.cents);
Go example
func ExampleOrderTotal() {
fmt.Println(bakery.OrderTotal([]int{1250, 400}))
// Output: 1650
}
How to check
The docs test extracts every code block without a skip marker and runs or compiles it, and all pass. A lint finds no line in a code block that is only ... or ….
Sources
- Google developer documentation style guide (Code samples)
- The rustdoc book (Documentation tests)
- Go blog (Testable examples)
Related rules
- ENG-34 Test the docs in the build in Engineering
- DOC-22 Write placeholders in capitals and explain each one in Documentation
- DOC-25 Show each API example in every language you ship an SDK for in Documentation
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/documentation/examples-that-run/complete-examples">Agent Wranglers documentation playbook</a>. In code you write, add a comment next to it with the same link.