The Best Documentation Behaves Like a Query Optimizer

Kai Nguyen

Hatched by Kai Nguyen

Aug 21, 2026

10 min read

91%

0

What if a docstring and a database query were solving the same problem?

At first, the comparison seems absurd. A docstring explains what code means. A SQL query retrieves rows from a table. One serves human understanding, the other serves computation. Yet both are attempts to reduce the cost of finding what matters inside a large system.

A good docstring helps a reader locate the essential truth of a function quickly. A good query helps a database locate the relevant records without examining everything. Both succeed when they expose the right structure early, avoid unnecessary work, and provide detail in layers.

This suggests a useful thesis: clarity is not merely a matter of presentation. It is a form of optimization. Whether the consumer is a programmer or a query planner, a well designed interface makes important information easy to identify and expensive work unnecessary.

Every interface imposes a search problem.

When someone encounters a function called calculate, they do not yet know what it calculates, what inputs it expects, what it returns, or what can go wrong. They must inspect the implementation, trace callers, infer assumptions, and perhaps run experiments. The function may be perfectly correct, but its meaning is expensive to retrieve.

A database faces a similar problem. Suppose a table contains ten million customer records and the system needs customers in a particular region. If the query is expressed in a way that prevents the database from using an index, the database may inspect rows one by one. The answer may still be correct, but the meaning of the request is expensive to execute.

In both cases, the central failure is not wrongness. It is avoidable search.

A one line docstring addresses this problem by placing a summary at the point of use. It is intended for cases whose meaning is obvious enough to fit on one line. When more explanation is needed, the summary comes first, followed by a blank line and a fuller description. This is more than a formatting convention. It is a retrieval strategy.

The reader gets the answer to the first question immediately: what does this object do? Only then are they invited into exceptions, constraints, examples, and background.

SQL optimization uses a related strategy. A searchable predicate allows the database to narrow the candidate set using an index. A condition such as:

WHERE customer_id = 1842

usually gives the database a direct route to the relevant records. A condition such as:

WHERE customer_id + 0 = 1842

may obscure that route by applying an operation to the indexed column. The logical request is equivalent, but the operational shape is worse.

The lesson is subtle: equivalent meaning does not guarantee equivalent cost. Two descriptions can identify the same result while making the consumer do radically different work.

Summary Lines and Searchable Predicates

The strongest connection between docstrings and SQL is the principle of making the important claim easy to use.

In a docstring, the summary line is a kind of human index. It tells a reader whether they need to keep reading. In a query, a searchable condition is a machine index. It tells the execution engine where to look. Both create a cheap first pass that prevents unnecessary exploration.

Consider a function that validates an email address:

def is_valid_email(value):
    """Return whether value has a syntactically valid email address."""

The summary is compact, direct, and operational. A reader does not need to inspect the regular expression to understand the basic contract. If the function has important limitations, they can follow in a fuller description:

def is_valid_email(value):
    """Return whether value has a syntactically valid email address.

    This checks syntax only. It does not verify that the domain exists,
    that the mailbox is reachable, or that the address belongs to a user.
    """

The first line acts like a selective filter. It answers the common question while preserving access to the unusual cases.

Poor documentation often fails in the same way as a poorly shaped query. It makes the consumer perform a transformation before the useful information becomes available. Compare these two descriptions:

def normalize_records(records):
    """This function is used in several parts of the ingestion pipeline and
    handles some special cases involving missing values and historical data."""

The reader must translate a vague narrative into a purpose. A clearer version is:

def normalize_records(records):
    """Convert raw records into the canonical ingestion format."""

The second version is not necessarily more complete. It is more searchable. The function's role can be recognized without parsing implementation history.

This gives us a practical concept: semantic SARGability. In database systems, a predicate is SARGable when it is shaped so an index can use it efficiently. In software communication, a statement is semantically SARGable when its main purpose is shaped so a reader can identify it without reconstructing the author's intent.

A semantically SARGable explanation tends to have four properties:

  1. It begins with the object's action or responsibility.
  2. It uses concrete verbs rather than vague descriptions of activity.
  3. It exposes the most decision relevant fact first.
  4. It postpones exceptions and history until after the core meaning is clear.

This is not an argument for simplistic writing. It is an argument for ordered complexity.

Detail Is Valuable, but Timing Matters

The danger of emphasizing summaries is that people may mistake brevity for quality. A one line docstring is not automatically good. It is appropriate only when the behavior is genuinely obvious or when the summary is followed by necessary detail.

Likewise, filtering early in a SQL query is not a universal command to remove all complexity. A query may require grouping, sorting, calculations, and joins. The question is whether those operations happen before the system has reduced the amount of data they must process.

This is the deeper shared pattern: do cheap discrimination before expensive interpretation.

Imagine a library containing one hundred thousand books. A librarian first checks the subject, then the author, then the title, and only afterward reads the relevant pages. Asking the librarian to read every book before deciding which one you wanted would be technically thorough and practically useless.

A query planner behaves similarly. It benefits when the request narrows the result set early, uses suitable indexes, avoids unnecessary sorting, and limits the amount of data carried into later operations. A human reader benefits when documentation gives the purpose first, then the contract, then the edge cases.

The order matters because later work compounds earlier ambiguity.

If a function's purpose is unclear, every sentence in its documentation becomes harder to interpret. If a query produces a huge intermediate result, every later sort or grouping operation becomes more expensive. In both domains, early structure controls downstream cost.

This also explains why negation and leading wildcards can be problematic for indexed columns. A condition such as:

WHERE status <> 'archived'

may be less useful to an index than a direct equality condition, because the database is being asked to find almost everything except a category. A condition such as:

WHERE name LIKE '%son'

makes it difficult to navigate an index from the beginning of the value, because the relevant information appears only at the end.

The communication equivalents are statements that define a concept by exclusion or bury its key distinction late in the sentence. For example:

This component is not exactly a cache, although it can sometimes be used in a caching context and has historically shared some implementation details with one.

The reader must travel through negation and context before learning what the component actually does. A more usable explanation might be:

This component stores temporary computation results for reuse. It is not intended to provide durable caching.

The positive identity comes first. The boundary follows.

The Two Layer Contract

A robust interface should serve two kinds of consumers: the consumer who needs an immediate answer and the consumer who needs a precise model.

For documentation, this means separating the recognition layer from the reasoning layer.

The recognition layer is the summary line. It allows a reader scanning a module, editor, generated reference page, or autocomplete panel to decide whether the object is relevant. It should be short enough to survive compact displays and specific enough to distinguish the object from its neighbors.

The reasoning layer contains the information needed to use the object safely. It may explain arguments, return values, side effects, exceptions, invariants, performance characteristics, and examples. The blank line between summary and description is conceptually important because it signals a change from quick identification to deeper inspection.

SQL has an analogous distinction between selecting candidates and processing them. An index helps identify candidates cheaply. Later operations verify, join, aggregate, or sort those candidates. The database does not eliminate reasoning. It delays expensive reasoning until the input is small enough to make it affordable.

This can be turned into a general design model:

Recognize first. Restrict second. Explain or compute deeply third.

For a function:

Summary -> contract -> edge cases -> examples

For a query:

Indexed filters -> joins -> calculations -> grouping and sorting

These sequences are not identical, and the analogy has limits. A human is not a database engine, and a docstring is not an execution plan. But the shared logic is powerful because both systems suffer when high cost arrives before high selectivity.

A useful review question follows: What is the cheapest operation that can eliminate the most uncertainty?

For a query, the answer may be an indexed equality filter. For documentation, it may be a single precise sentence. For an API, it may be a clearly named parameter. For a code review, it may be a statement of the invariant that the implementation must preserve.

Designing for the Consumer's First Move

The practical consequence is that we should design interfaces around the consumer's first move, not the creator's full knowledge.

A developer writing a function knows its history, compromises, and internal machinery. Those facts are psychologically available, so they often leak into the explanation. But the next reader does not need the journey first. They need a reliable destination.

Similarly, a query author may think in terms of the desired final report and write expressions that mirror the report's visual structure. The database, however, needs a shape that supports efficient access. The most natural formulation for a human is not always the most useful formulation for an execution engine.

The solution in both cases is to distinguish intent from access path. The intent says what result is wanted. The access path determines how cheaply the consumer can obtain or understand it.

For documentation, test the access path by scanning only the summary lines. Can a reader tell which function to choose? Can they distinguish similar functions? Do the first words reveal the action?

For SQL, inspect the execution plan rather than trusting the query's surface elegance. Is an appropriate index being used? Are calculations applied to indexed columns? Is a leading wildcard preventing efficient lookup? Is the query sorting or grouping more data than necessary? Is the result set larger than the caller actually needs?

The same discipline applies to both: measure the route, not just the destination.

Key Takeaways

  • Write the first sentence of a docstring as a retrieval tool. State what the object does, using a concrete verb and a direct subject.
  • Put the common answer before the exceptional details. Summary first, blank line, then contract, limitations, and examples.
  • Look for semantic transformations that force the consumer to work before finding the main point. These include vague introductions, buried definitions, unnecessary negation, and history presented before purpose.
  • In SQL, shape conditions so indexes can use them. Avoid applying arithmetic or functions to indexed columns, leading wildcards, unnecessary negation, excessive sorting, and oversized result sets.
  • Review interfaces by asking what the consumer must do first. Optimize that first move before polishing the rest.

The most important shift is to stop treating documentation and query performance as separate concerns. Both are expressions of a broader engineering principle: make the useful distinction early.

A system becomes easier to use when it does not force every consumer to inspect everything. A reader should not have to parse an entire explanation to discover the function's purpose. A database should not have to scan an entire table to discover the rows that matter. In each case, a small amount of well placed structure creates an index over complexity.

Good writing, then, is not decoration added after the real engineering is complete. It is part of the access path. A precise summary is a human facing index. A well shaped predicate is a machine facing summary. Both reduce the distance between a question and the answer.

The best interfaces do not merely contain the right information. They arrange it so that the right consumer can reach the right information with the least unnecessary work.

Sources

← Back to Library

Hatch New Ideas with Glasp AI 🐣

Glasp AI allows you to hatch new ideas based on your curated content. Let's curate and create with Glasp AI :)

Start Hatching 🐣
The Best Documentation Behaves Like a Query Optimizer | Glasp