Code Documentation
Document code so that it explains intent and constraints: naming, comments that add value, docstrings for public interfaces, tested examples, module overviews, and a generated reference.
Introduction
Code tells the machine what to do and tells people what the code does. It rarely tells them why, what was ruled out, what must not change, or what the caller is allowed to assume. Code documentation fills exactly that gap.
Done badly, it is noise: comments that restate each line and rot as the code changes. Done well, it is the cheapest, most local, and most durable form of documentation, because it sits next to the thing it explains.
Learning Objectives
- Decide what belongs in the code, in docstrings, and in separate documents.
- Use naming and structure as the first layer of documentation.
- Write comments that explain why, and remove comments that restate what.
- Write docstrings for public interfaces: purpose, parameters, results, errors, and examples.
- Make examples executable.
- Document modules and packages, and generate a reference.
- Use AI to draft code documentation without inventing intent.
1. Where Each Kind of Knowledge Belongs
| Knowledge | Best home |
|---|---|
| What a thing is and does | Its name and types |
| How to use a public function or class | Docstring (generated into the reference) |
| Why this line is written this way | Inline comment next to it |
| What a module is for and how its parts relate | Module docstring or short overview file |
| How the system is structured | Architecture documentation (lesson 6) |
| Why a significant decision was made | Decision record (lesson 7) |
| How to run, build, and contribute | README and developer guide (lesson 8) |
Put information at the lowest level where it stays true and findable. A rule about one function belongs on the function. A rule about the whole system belongs elsewhere, and a comment in one function that describes the whole system will go stale.
2. Names and Structure First
Many comments are apologies for unclear code. Before writing a comment, try to remove the need for it.
1
2
3
4
5
6
7
8
9
10
# Before
def proc(r, f):
# check f
if f and not r["b"].strip():
return None
...
# After
def validate_row(row: FeedbackRow, *, require_body: bool = True) -> ValidationResult:
...
- Name by intent and domain vocabulary, using the glossary terms.
- Prefer small functions with one purpose, so that the function name is a summary.
- Use types to document shapes and optionality.
- Extract a named constant or function for a “magic” value or condition:
MAX_BODY_LENGTH = 10_000documents itself.
Clear code does not remove the need for documentation; it removes the need for low-value documentation.
3. Comments That Earn Their Place
Good comments explain:
- Why: the reason for an approach, especially if it looks odd.
- Constraints and invariants: what must stay true.
- Warnings: performance traps, ordering requirements, non-obvious side effects.
- References: the ticket, standard, ADR, or bug that motivates the code.
- Trade-offs: what was considered and rejected.
1
2
3
4
# Fingerprint uses the normalized body plus the source and date, not the
# customer's own row ID: exports from the same tool reuse IDs across
# files, which caused false duplicates in the pilot (see ADR-0007).
fingerprint = hash_fields(normalize(row.body), row.source, row.date)
Bad comments:
1
2
3
4
5
6
7
# increment counter
count += 1
# TODO: fix this later (no owner, no ticket, no date)
# Old logic, keep just in case (version control already remembers)
# if legacy_mode: ...
Rules of thumb:
- A comment that restates the code should be deleted or replaced by a better name.
- A TODO needs a ticket reference, or it is a lie about the future.
- Delete commented-out code.
- When you change code, change the comment in the same edit. A wrong comment is worse than none.
4. Docstrings for Public Interfaces
A docstring documents an interface for those who call it. It should let a caller use the function without reading its body.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def validate_row(row: FeedbackRow, *, require_body: bool = True) -> ValidationResult:
"""Check a single imported feedback row against the import rules.
Validation never raises for bad input; problems are reported in the
result so that one bad row does not stop an import.
Args:
row: The parsed CSV row. Fields are strings and may be empty.
require_body: If True (the default), a row whose body is empty or
only whitespace is rejected.
Returns:
A ValidationResult. ``ok`` is True when the row may be imported.
Otherwise ``code`` is one of ``MISSING_BODY``, ``BODY_TOO_LONG``,
or ``INVALID_DATE``, and ``message`` is suitable to show to a user.
Raises:
TypeError: If ``row`` is not a FeedbackRow (a programming error).
Example:
>>> validate_row(FeedbackRow(body=" ", source="email", date="2026-11-02")).code
'MISSING_BODY'
"""
A useful docstring contains:
| Element | Content |
|---|---|
| Summary line | What it does, in one sentence, in the imperative |
| Behavior notes | Anything non-obvious: side effects, idempotency, performance, thread-safety |
| Parameters | Meaning, units, allowed values, defaults |
| Returns | What and in which shape, including special values |
| Errors | What is raised or returned, and when |
| Example | Short and runnable |
Document the contract: what callers may rely on and what they must provide. Do not describe the implementation, which would force you to update the docstring on every refactor.
Which interfaces need docstrings? Public functions, classes, and modules that other code or people depend on, and any internal code with non-obvious behavior. Not every private helper needs one; a good name usually suffices.
5. Executable Examples
An example in a docstring that is never run is a future inaccuracy. Run them.
1
2
# Doctest style: the example above runs as a test
python -m pytest --doctest-modules src/
Where an example is too large for a docstring, put it in a test file and include it in the documentation from there. Examples then double as tests and stay correct by construction (lesson 3).
6. Module and Package Documentation
A module docstring or short README.md in a package directory answers: What is this for? What does it own? What does it depend on? What should I read first?
1
2
3
4
5
6
7
8
9
10
"""Feedback import: parsing, validation, and deduplication of CSV files.
Owns the rules for what counts as an acceptable feedback row. Does not
touch the database; persistence is handled by ``signaldesk.storage``.
Start with ``pipeline.run_import``. Rules live in ``validation``;
duplicate detection in ``fingerprint``.
See also: docs/architecture/runtime-views.md (import flow), ADR-0007.
"""
Link to architecture documentation and decisions instead of repeating them. Include the boundaries (what the module does not do), because that is the information a newcomer most needs.
7. Generated Reference
Generate a browsable reference from docstrings and type hints with the tools of your ecosystem (for example Sphinx or MkDocs with a docstring plugin for Python, Javadoc for Java, TypeDoc for TypeScript, godoc for Go). Include it in the documentation build so that:
- Missing docstrings on public interfaces can fail a check (use a docstring coverage tool or lint rule with a sensible threshold, as a diagnostic and not a vanity metric).
- The reference is versioned with the code.
- Cross-references between functions and types work.
Generated reference answers “what is the signature and contract.” It never replaces guides and explanation.
8. Documenting Legacy and Unfamiliar Code
When you inherit code with no documentation, the way to write it is to learn it first (see the legacy code lesson in the software development course):
- Read the entry points and trace one real scenario end to end.
- Write characterization tests that record current behavior.
- Document what you confirmed as you learn it: the module overview first, then docstrings for the interfaces you touch.
- Mark uncertainty honestly: “Behavior when
sourceis empty is not confirmed (see issue 214).”
Do not document intent you have guessed. If the reason for something is unknown, write that.
9. Using AI for Code Documentation
AI sees the code, which is exactly why it tends to produce docstrings that restate the code. The value comes from asking for contracts and questions, not for descriptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Act as a senior engineer documenting code for other engineers.
Inputs:
- Source file or function: [paste]
- Tests for it: [paste]
- Related decision records, tickets, or requirements: [paste]
- Docstring style and glossary: [paste]
Tasks:
1. Draft a docstring for each public function and class: summary,
parameters, returns, errors, and a short example.
2. Describe behavior only as visible in the code or tests. Do not
describe internal steps unless callers depend on them.
3. List behaviors that appear intentional but whose reason is not
documented anywhere, as questions for the author (do not guess
the reason).
4. List edge cases the code handles that the tests do not cover.
5. Flag any discrepancy between the code, the tests, and the
existing comments.
6. Propose names that would remove the need for a comment, where
applicable.
Do not invent intent, limits, or guarantees. Use [UNKNOWN] where
unsure.
Also useful:
- Review existing comments: ask the model to list comments that restate code, contradict it, or reference things that no longer exist.
- Explain-the-why interview: have the model ask the author five questions about a tricky function, then turn the author’s answers into a comment. The author supplies the reason; the model improves the wording.
- Examples: ask for doctest-style examples, and run them.
Verify docstrings by calling the function the way the documentation says. If an example fails, the docstring or the code is wrong.
10. Practical Exercise
For SignalDesk (or your project):
- Choose the import module and its public interface. Improve names and extract constants where that removes the need for comments.
- Review existing comments: delete the ones that restate code, fix the ones that are wrong, and convert vague TODOs to tickets.
- Add docstrings to every public function and class, including errors and an example.
- Add a module overview for the package, including its boundaries and links.
- Run the AI prompt, check each suggestion against the code and tests, and answer the “undocumented reason” questions yourself.
- Enable doctests in the test run, and generate the reference in the documentation build.
- Add a docstring check for public interfaces, and decide the threshold deliberately.
- Ask a teammate to use two of the functions from the generated reference only, and record where they are confused.
Verification
You are ready to continue when:
- Public interfaces have docstrings that state purpose, parameters, results, errors, and an example.
- Examples run as tests and pass.
- No comment restates the code, contradicts it, or hides a vague TODO.
- Every module has a short overview with boundaries and links to architecture and decisions.
- The generated reference builds with the documentation and is versioned with the code.
- Rationale in comments came from the author or a decision record, not from a guess.
Key Takeaways
- Put knowledge at the lowest level where it stays true and findable.
- Names and structure are the first documentation; comments explain why, not what.
- A docstring states the contract so that callers need not read the body.
- Executable examples stay correct; unexecuted examples rot.
- AI is good at drafting contracts and asking questions; the author supplies intent.
What’s Next?
Code documentation explains the parts. Next, we document the whole: how SignalDesk is structured, how its pieces interact, and which concerns cut across them, in a form that new engineers, operators, and reviewers can actually use.