Code Documentation Example: Comments to README

November 11, 2026 · 13 min read

Code Documentation Examples: Comments, Doc Comments and READMEs

A good code documentation example explains one piece of code at every layer it touches. An inline comment says why, a doc comment lists inputs and outputs, a file header says what the module owns, and a README shows usage. Below, one small function gets all four layers, written badly first and then well.

What Is an Example of Code Documentation?

Code documentation is any text that travels with the code and helps the next person use or change it. It comes in layers, and each layer has a different reader. Mixing them up is a common reason docs feel useless: a README that explains a regex, or a comment that repeats the function name.

LayerWho reads itWhere it livesQuestion it answers
Inline commentThe next person editing that lineBeside the codeWhy is it done this way?
Doc commentAnyone calling the functionDirectly above the declarationWhat goes in, what comes out, what can fail?
File or module headerSomeone opening the file for the first timeTop of the fileWhat does this file own, and what doesn't it?
READMEA new user or contributorRepository rootHow do I install and use this?

The running example is slugify, a helper that turns a title like "Crème brûlée" into creme-brulee for a URL. It's short enough to read in one glance and has one genuinely surprising line, which is exactly where documentation earns its keep.

Inline Comments That Explain Why, Not What

An inline comment should tell the reader something the code can't. Here's the version most codebases have:

// convert to lowercase
.toLowerCase()
// replace non-alphanumeric characters with spaces
.replace(/[^a-z0-9]+/g, ' ')

Both comments restate the method name. They add reading time and nothing else, and they go stale the moment someone edits the line. Compare a comment on the line that actually needs one:

// Strip accents before the next step, or "Crème brûlée" becomes
// "cr-me-br-l-e". NFKD splits each accented letter into a base
// letter plus a combining mark, and the regex removes the marks.
.normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')

That comment records a decision and the bug it prevents. Delete it and someone will "simplify" those two lines away. We ran both versions in Node, and without the normalisation step the output really is cr-me-br-l-e.

Two habits keep inline comments honest. If a comment explains what a variable holds, rename the variable instead (d becomes daysUntilExpiry). When you leave a TODO, give it an owner and a ticket, such as // TODO(priya, #482): remove once titles arrive normalised. Then it can't sit there anonymously for years. When a line works around a bug in a dependency, link the upstream issue in the comment. Then whoever upgrades that dependency knows the workaround can go.

Doc Comments in JSDoc, Python, Javadoc and Go

A doc comment sits directly above a function and describes its contract: parameters, return value and errors. Tools read it, so the syntax matters. Here's the same function documented in four languages.

JavaScript (JSDoc). Tags start with @, and types go in curly braces. Square brackets mark an optional parameter with its default, per the JSDoc @param reference.

/**
 * Converts text into a lowercase, URL-safe slug.
 *
 * @param {string} text - The title or phrase to convert.
 * @param {string} [separator='-'] - Placed between words.
 * @returns {string} The slug, e.g. 'creme-brulee'.
 * @throws {TypeError} If text is not a string.
 */
function slugify(text, separator = '-') {

The jsdoc command turns these blocks into HTML pages, and editors such as VS Code show them in hover tooltips.

Python (docstring). PEP 257 says a docstring is the first statement in the function, uses triple double quotes, and opens with a one-line summary ending in a period. The sections below follow the Google style guide.

def slugify(text: str, separator: str = "-") -> str:
    """Convert text into a lowercase, URL-safe slug.

    Args:
        text: The title or phrase to convert.
        separator: Placed between words.

    Returns:
        The slug, for example 'creme-brulee'.

    Raises:
        TypeError: If text is not a string.
    """

The string becomes the function's __doc__ attribute, so help(slugify) prints it. Sphinx field lists and the NumPy style are alternatives; pick one per project and stick to it.

Java (Javadoc). The javadoc tool copies the first sentence into the summary table, so make that sentence stand alone.

/**
 * Converts text into a lowercase, URL-safe slug.
 *
 * @param text      the title or phrase to convert
 * @param separator the string placed between words
 * @return the slug, for example {@code creme-brulee}
 * @throws NullPointerException if text is null
 */
public static String slugify(String text, String separator) { ... }

Go. Go has no tags. The Go doc comment guide asks for complete sentences placed immediately before the declaration, and the Go code review notes say a comment should begin with the name it describes.

// Slugify converts text into a lowercase, URL-safe slug, placing sep
// between words. Accents are stripped, so "Crème brûlée" becomes
// "creme-brulee".
func Slugify(text, sep string) string { ... }

Parameters are named in plain prose, and go doc Slugify prints the comment in your terminal.

Whatever the language, three things stay out of a doc comment. Implementation details belong in inline comments, because callers shouldn't depend on them. History belongs in version control, not in lines like "changed by Sam in March". And types the signature already declares don't need repeating in prose, which is why the Python and Go versions skip them.

File and Module Headers: What This Code Owns

A file header answers the first question anyone asks on opening a file: what is this for? Keep it to three things: what the module owns, what it deliberately leaves to other code, and where the reasoning lives. JSDoc uses the @file tag for this.

/**
 * @file Slug helpers for article URLs.
 *
 * Owns: turning titles into slugs.
 * Does not: check uniqueness or write redirects (see routes/redirects.js).
 * Background: ADR-012, Stable article URLs.
 */

The "does not" line often saves the most time. It stops a newcomer from adding database calls to a pure string helper.

Go builds this layer into the language's conventions. A package comment sits above the package clause and starts with the word "Package":

// Package slug turns titles into URL-safe slugs.
//
// It doesn't check uniqueness; callers do that against their own store.
package slug

In Python, the module docstring does this job. It's the first statement in the file, and PEP 257 suggests it list what the module exports.

How Do You Document Your Code? A Before and After Pass

You document code in passes, starting with the code itself and ending with the README. If you're asking how to write code documentation for a function that already exists, this order works because each step removes work from the next one. Here's the function as it might look today:

// format title
function fmt(t, s = '-') {
  // check type
  if (typeof t !== 'string') throw new TypeError('bad input');
  return t
    .normalize('NFKD')
    .replace(/[\u0300-\u036f]/g, '') // replace
    .toLowerCase() // lowercase
    .replace(/[^a-z0-9]+/g, ' ')
    .trim()
    .split(' ')
    .join(s); // join
}
  1. Rename. fmt becomes slugify, t becomes text, s becomes separator. The error message names the function.
  2. Cut comments that echo the code. "format title", "check type", "lowercase" and "join" all go.
  3. Write the one why comment. The accent-stripping line is the only surprise, so it gets the comment.
  4. Add the doc comment, including an @example that shows a real input and output.
  5. Add the README section and a test, covered in the next two sections.

After the pass:

/**
 * Converts text into a lowercase, URL-safe slug.
 *
 * @param {string} text - The title or phrase to convert.
 * @param {string} [separator='-'] - Placed between words.
 * @returns {string} The slug.
 * @throws {TypeError} If text is not a string.
 * @example
 * slugify('Crème brûlée'); // 'creme-brulee'
 * slugify('Hello, World!', '_'); // 'hello_world'
 */
export function slugify(text, separator = '-') {
  if (typeof text !== 'string') {
    throw new TypeError('slugify expects a string');
  }
  return text
    // Strip accents first, or "Crème brûlée" becomes "cr-me-br-l-e".
    .normalize('NFKD')
    .replace(/[\u0300-\u036f]/g, '')
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, ' ')
    .trim()
    .split(' ')
    .join(separator);
}

The function has more lines than before, yet it's faster to read, and every comment line carries information. This is also how to write documentation for code you inherited: rename and delete first, then add.

A Complete Code Documentation Example: The README Usage Section

The README is the layer people see before they read any code. For a single helper, one usage section is enough. Here's the README layer of a complete code documentation example, written in Markdown.

## slugify(text, separator)

Turns a title into a lowercase, URL-safe slug.

| Parameter | Type | Default | Description |
|---|---|---|---|
| text | string | required | The text to convert |
| separator | string | `-` | Placed between words |

**Returns:** the slug as a string.

**Throws:** `TypeError` when `text` is not a string.

```js
import { slugify } from './slug.js';

slugify('Crème brûlée');       // 'creme-brulee'
slugify('Hello, World!', '_'); // 'hello_world'
```

The parameter table mirrors the doc comment, and the code block shows the two calls a reader is most likely to copy. Nothing here explains how the function works inside, because that stays in the code. Tag the usage fence with a language, as our Markdown code block guide shows, so GitHub knows how to colour it.

A full README also needs a title, install steps and a license, which our README Markdown guide covers section by section. To skip the blank page, the README generator builds a starting file in your browser from one of five templates (library, cli, api, webapp and profile).

Edit the usage section below and watch the table and code block render:

slugify(text, separator)

Turns a title into a lowercase, URL-safe slug.

Parameter Type Default Description
text string required The text to convert
separator string hyphen Placed between words
slugify('Hello, World!')
// hello-world

Returns: the slug as a string.

Throws: TypeError when text is not a string.

64 words381 characters16 lines
Markdown

One limitation to know: our editor's preview shows the code block as plain, uncoloured text. GitHub adds syntax colouring when it renders the README, so check the final look there.

Usage Snippets, Doctests and Tests as Living Examples

Examples are often the first thing a reader copies, and the part most likely to rot. The fix is to make them executable wherever the language allows it.

JSDoc's @example tag, shown in the after version above, is only displayed: the jsdoc tool never runs it. Python goes further. The doctest module finds interactive >>> sessions inside docstrings and runs them:

def slugify(text, separator="-"):
    """Convert text into a lowercase, URL-safe slug.

    >>> slugify("Hello, World!")
    'hello-world'
    >>> slugify("Crème brûlée", separator="_")
    'creme_brulee'
    """

With the function body in place, run python -m doctest -v slug.py and a wrong example fails like any other test. Rust's rustdoc does the same for code blocks in doc comments.

For everything else, your test names are documentation too. A test called strips accents so French titles stay readable tells the next developer why the NFKD line exists, and it fails loudly if someone removes it. Reference pages for a whole HTTP API are a different genre; see the API section of our Markdown documentation guide for that. For real ones to study, see these examples of API documentation from Stripe, GitHub and Twilio.

Keeping Comments and Docs Accurate After Refactors

Wrong documentation is worse than none, because readers trust it. A few rules keep the layers in step:

  • Change docs in the same pull request as the code. A docs follow-up ticket rarely gets picked up. That habit is the core of a docs as code workflow.
  • Make reviewers read comments, not skip them. "Does this comment still match the code?" belongs on the review checklist.
  • Delete stale comments outright. Version control remembers them if you ever need them back.
  • Keep editorial notes out of rendered docs. In Markdown files, hidden Markdown comments hold reminders that readers never see.

We prefer one honest sentence of why over a five-line comment that restates the code. Short comments get read and updated; long ones get skipped.

The honest limitation: no comment survives a refactor nobody reviews. Generated reference docs only repeat what you wrote in the doc comments, so a generator won't rescue a vague @param line.

The pattern carries over to any codebase. Name things well, comment only the surprises, give every public function a doc comment, head each file with what it owns, and show real usage in the README. Use this code documentation example as a checklist for your next pull request. Draft the README section in the editor and check the table and code block in the live preview before you commit it.