Code Documentation: Types, Examples and Best Practices

Raghav Chamadiya9 min read
On this page

Code documentation is the written explanation that lives alongside source code: inline comments, docstrings, READMEs, API references, architecture overviews and decision records. It tells a reader what a piece of code is for, how to use it and why it was built that way, so they can change it without reverse-engineering it first.

Good documentation is mostly about the "why", because the code already shows the "what". This guide covers the types, real examples in Python, JavaScript and Go, the practices that keep docs useful, how to generate documentation from code, and how to stop it going stale.

What is code documentation?

Code documentation is any text written to explain code to the people who use, review or maintain it. It splits into two audiences. Documentation for users of the code (API references, READMEs, usage guides) explains how to call it. Documentation for maintainers (comments, architecture docs, decision records) explains how it works inside and why.

It is different from technical writing for end users, such as product manuals and help centers. Code documentation sits in or next to the repository and changes with the code.

Types of code documentation

Six types cover nearly every codebase; each answers a different question at a different distance from the code.

TypeLives inAnswersWritten for
Inline commentsThe source line or blockWhy this line is unusualMaintainers
Docstrings and doc commentsAbove a function, class or moduleWhat it does, its parameters, returns and errorsCallers and IDE tooltips
READMEThe repository or package rootWhat this is, how to install, run and test itNewcomers
API referenceGenerated site or docs/Every public function and type, in one placeLibrary users
Architecture docsdocs/, a wikiHow the parts fit: modules, data flow, boundariesNew team members
Architecture decision records (ADRs)docs/adr/ or similarWhy a design was chosen over the alternativesFuture maintainers

Scroll the table sideways to see every column.

Most teams write the first three and skip the last two, which are the ones a new engineer needs most. Formal ADRs are rare even in mature projects: across 190 popular open-source repos, at least 10 have ADR files, while 154 record design decisions in pull request descriptions and 163 in commit messages (where architecture decisions live).

Code documentation examples

The examples below follow each language's own conventions, which is what the documentation generators and IDEs read. For templates of whole documents such as runbooks, design docs and ADRs, see technical documentation examples.

A Python docstring in Google style, which Sphinx reads through the napoleon extension:

python
def retry(fn, attempts=3, backoff=0.5):
    """Call fn until it succeeds or attempts run out.

    Retries only on ConnectionError. Other exceptions propagate on the first
    failure, because they mean the request itself is wrong.

    Args:
        fn: Zero-argument callable to run.
        attempts: Total tries, including the first. Must be at least 1.
        backoff: Seconds to wait before the second try; doubles each retry.

    Returns:
        Whatever fn returns on its first successful call.

    Raises:
        ConnectionError: If every attempt fails.
    """

A JSDoc comment, which TypeScript, VS Code and TypeDoc all read:

javascript
/**
 * Format a price in the customer's currency.
 *
 * Uses Intl.NumberFormat instead of toFixed so that currencies with no minor
 * unit (JPY) and three-digit minor units (KWD) render correctly.
 *
 * @param {number} amount - Amount in minor units (cents for USD).
 * @param {string} currency - ISO 4217 code, e.g. "USD".
 * @returns {string} The formatted price, e.g. "$12.50".
 */
export function formatPrice(amount, currency) { /* ... */ }

A Go doc comment, which go doc and pkg.go.dev render. It starts with the name it documents:

go
// ParseDuration parses a duration such as "90s" or "1h30m".
//
// Unlike time.ParseDuration it accepts "d" for days, because our config files
// use them; a day is always 24 hours, ignoring DST.
func ParseDuration(s string) (time.Duration, error) {

A README skeleton that answers a newcomer's first questions in order:

markdown
# payments-service

Charges cards and issues refunds for the checkout flow. Owns the `payments` schema.

## Run it locally
## Run the tests
## How it fits in        (who calls it, what it calls, link to the architecture doc)
## Configuration         (every env var, with its default)
## Decisions             (link to docs/adr/)

Note what each example spends its words on: the retry policy's reason for not retrying everything, the currency edge cases, the DST rule. Those are the facts a reader cannot get from the signature.

Code documentation best practices

Document why, keep docs next to the code they describe, and review them in the same pull request as the code. In more detail:

  1. Explain why, not what. i += 1 # increment i adds nothing. # skip the header row explains intent. The best comment names a constraint the code cannot show: a bug in a dependency, a business rule, a performance reason. Names and types can carry the "what", but not the "why", which is the argument in self-documenting code.
  2. Document the contract at the boundary. Every public function, class and module gets a docstring with parameters, return value, errors and side effects. Private helpers need one only when the name is not enough.
  3. Keep docs close to the code. A docstring changes in the same diff as the function. A wiki page on another system does not, which is why it drifts first.
  4. Review docs in pull requests. If a change alters behavior, the reviewer checks that the docstring, README and API reference still match. Make it a checklist item.
  5. Write the README for the first hour. Install, run, test, and where to read next. Anything longer goes in docs/.
  6. Record decisions when you make them. A short decision record or a clear pull request description written the day of the decision is worth more than a design document reconstructed a year later.
  7. Delete wrong docs. A missing comment costs a reader time. A wrong one costs them a bug.

How to generate code documentation

Documentation generators read the docstrings and doc comments already in your code and build a browsable API reference. Pick the standard one for your language:

LanguageGeneratorCommand
PythonSphinx with autodoc, or pdocsphinx-build -b html docs/ docs/_build / pdoc mypackage
TypeScript, JavaScriptTypeDoc, JSDocnpx typedoc src/index.ts
Gogo doc, pkgsitego doc ./... locally; pkg.go.dev publishes public modules
Rustrustdoccargo doc --open
JavaJavadocjavadoc -d docs src/**/*.java
C, C++ and many othersDoxygendoxygen Doxyfile

Scroll the table sideways to see every column.

These generators document the API surface: one page per module, function and type, filled from what the authors wrote. They do not explain how modules depend on each other, which files matter most, or how a request flows through the system, and they are only as complete as the docstrings.

Wiki generation fills that gap. A tool reads the code, its dependency graph and its git history, and writes pages for files, modules and architecture. repowise does this, and the AI options are compared in auto-generating codebase documentation.

Why docs go stale and how to keep them current

Documentation goes stale because code changes in a pull request and nothing forces the docs to change with it. A function gets renamed, a heading moves, a script is deleted, and every page that mentions them is now wrong. Nobody notices until a new engineer follows the instructions.

Three habits slow the drift: keep docs in the repository so they show up in diffs, put a docs check in the pull request template, and give each doc an owner. The reliable fix is to check docs against the code automatically, the same way tests check behavior. The stale documentation guide covers the methods in depth.

How repowise documents code and catches drift

repowise generates a wiki from the code itself, updates the pages each commit touched, and checks existing docs against the code for drift. At index time it writes a page per source file, per selected public symbol, per subsystem, per dependency cycle and per API surface, plus a repository overview and an onboarding reading order (wiki docs). Most pages are rendered from the code's structure with no model involved; a provider key adds prose to the subsystem and overview pages. Every claim links to the lines it came from.

For the docs your team writes, repowise doc-drift checks five kinds of claims against the code: file paths, links between documents, links to headings, commands, and symbol names that git proves existed when the line was written (doc drift docs). In CI it needs no index and no model:

bash
repowise doc-drift --check --format github

It exits non-zero when a document references something the code no longer has, and annotates the pull request. Read a generated wiki on a live repo at fastapi/fastapi, or see the wiki feature page. For a team rollout, the codebase documentation guide covers what to write by hand and what to generate.

FAQ

How do you generate code documentation?
Write docstrings or doc comments in your language's standard format, then run its generator: Sphinx or pdoc for Python, TypeDoc for TypeScript, go doc for Go, cargo doc for Rust, Javadoc for Java or Doxygen for C and C++. For architecture-level documentation of files and modules, use a wiki generator that reads the code and its dependency graph.
What should code documentation include?
At minimum, a README with what the project is and how to install, run and test it, and docstrings on every public function covering parameters, return values, errors and side effects. Add comments where the code does something non-obvious and say why. Larger codebases also need an architecture overview and a record of key design decisions.
What is the 40/20/40 rule in software engineering?
It is an informal rule of thumb that splits project effort into about 40% planning and design, 20% coding and 40% testing. It has no single canonical source, and some teams use the same name for a roadmap split. For documentation, the point is that design notes and decision records written in the first 40% are what later readers need most.
Should comments explain what or why?
Comments should explain why. Well-named code already shows what it does, so a comment that restates it goes stale and adds noise. Use comments for intent, constraints and trade-offs, such as a workaround for a library bug or a business rule, and use docstrings to describe the contract of a function.
What tools generate documentation from code?
Sphinx, pdoc, TypeDoc, JSDoc, go doc and pkgsite, rustdoc, Javadoc and Doxygen generate API references from doc comments. Wiki generators such as repowise go further and write pages for files, modules, dependency cycles and the overall architecture, and keep them updated as the code changes.