The Hidden Engineering Principle Behind Fast Queries and Readable Code

Kai Nguyen

Hatched by Kai Nguyen

Sep 06, 2026

11 min read

93%

0

Why do some programs feel effortless to understand while others make even simple questions expensive? The answer may have less to do with intelligence, elegance, or performance tricks than with a quieter design principle: make the useful meaning easy to find.

A database query and a Python docstring seem to belong to different worlds. One governs how machines locate rows. The other helps humans interpret code. Yet both reward the same discipline. They work best when information is arranged so that the intended question can be answered early, directly, and without unnecessary transformation.

This suggests a broader idea: good software is searchable at every level. Its data can be searched efficiently, its behavior can be understood quickly, and its structure guides both machines and people toward the relevant answer.

That connection reveals a practical theory of software design. Performance and readability are not separate virtues. They are two forms of reducing the cost of retrieval.

Imagine a warehouse with ten million boxes. Finding one particular box is easy if every box has a clear label and the shelves are organized by a useful key. It is much harder if every label has been wrapped in an opaque transformation, if the boxes are arranged randomly, or if the warehouse requires you to inspect every item before deciding which one matters.

A database optimizer faces an analogous problem. An index can make a query fast because it gives the database a structure for locating relevant rows without examining the entire table. But the structure is useful only when the query expresses its condition in a form that the index can exploit.

This is the logic behind SARGability, the ability of a search condition to use an index effectively. A condition such as:

WHERE customer_id = 4172

gives the database a direct path to the desired records. A condition such as:

WHERE customer_id + 0 = 4172

may look equivalent to a human, but it introduces an operation around the indexed column. Depending on the database and its optimizer, that operation can make the index less useful because the system must evaluate the expression rather than navigate directly to the key.

The same pattern appears in less obvious forms. Applying a function to an indexed column, using a leading wildcard in a text search, or expressing a condition through negation can make a direct lookup more difficult. The logical meaning may remain unchanged, but the path to that meaning becomes more expensive.

This distinction matters far beyond databases. Software is full of information that exists but is difficult to retrieve. A function may do exactly what it claims, yet force a reader to inspect its implementation, surrounding state, and call sites before understanding its purpose. A module may contain excellent code, yet bury the central explanation in a long comment that must be read from beginning to end.

In both cases, the problem is not absence of information. It is poor access to information.

A system becomes efficient when its most important answers are available through the shortest trustworthy path.

Docstrings Are Indexes for Human Attention

A well designed docstring performs a role surprisingly similar to a database index. It does not contain every fact about a function. It places the most useful fact where a reader can find it immediately.

Consider two descriptions of a function:

def normalize_email(address):
    """Normalize an email address for comparison."""

And:

def normalize_email(address):
    """This function takes an address and performs a series of operations.

    It was originally introduced when the account system was redesigned.
    There are several edge cases involving whitespace and capitalization.
    The function is used in multiple places throughout the application.
    """

The second description may contain useful background, but it delays the answer to the reader's first question: what is this for? The first line of a docstring functions like a highly selective search condition. It identifies the purpose before the reader pays the cost of deeper inspection.

This is why a summary line is so powerful. It is not merely a formatting convention. It is an attention index. Tools can display it in generated documentation. Editors can surface it during autocomplete. A developer scanning a file can use it to decide whether the implementation deserves further investigation.

The rule that one line should be used for obvious cases also reveals an important design judgment. Brevity is valuable when the idea is genuinely simple. It becomes harmful when it hides distinctions that affect use, safety, or interpretation. A useful docstring therefore has two layers:

  1. A compact statement that answers the immediate question.
  2. A fuller explanation that becomes available when the immediate answer is not enough.

This layered structure resembles a well designed query plan. First, reduce the candidate set. Then perform the more expensive work only on the rows that survive the early filter. In documentation, the summary line filters the reader's attention. The detailed description is the expensive operation reserved for readers who need it.

The parallel is more than poetic. Every human interaction with code has a cost. Reading, remembering, comparing, and interpreting all consume limited cognitive resources. A docstring that leads with its purpose reduces the number of unnecessary mental operations. It lets the reader decide quickly whether to continue.

Syntax Is an Information Architecture

It is tempting to treat syntax as a surface concern. Use a particular quoting style, put a summary first, avoid an expression on an indexed column, and move on. But these conventions work because they encode an architecture of access.

A query is not only a statement of what data is wanted. It is also a suggestion about how the system should find it. Similarly, a docstring is not only a statement of what code does. It is also a suggestion about how a human should approach that code.

The important question is therefore not merely, "Is this equivalent?" It is:

Does this form preserve a direct route to the answer?

Two expressions can be logically equivalent while having very different retrieval costs. For a database, the difference may be whether an index can be used. For a reader, the difference may be whether purpose is visible in the first sentence or concealed beneath historical context.

Consider a function that validates a payment request. A weak opening might say:

"""Handle payment requests from the checkout process."""

This is vague. Does it validate, authorize, charge, log, or retry? A more searchable opening would say:

"""Validate payment fields and return structured validation errors."""

The second version exposes the function's contract. It tells the reader what kind of result to expect and distinguishes validation from neighboring responsibilities. The function has become easier to locate conceptually, just as a well formed predicate makes rows easier to locate physically.

The same principle applies to parameters, exceptions, and side effects. A detailed description should answer the questions that change how the function may safely be used:

  • Which inputs are accepted?
  • What does the return value represent?
  • What errors can occur?
  • Does the function mutate state?
  • Are there performance or ordering assumptions?

These are not decorative details. They are the semantic equivalent of index keys. They allow a reader to rule possibilities in or out without reconstructing the entire implementation.

Good documentation does not attempt to describe everything. It identifies the dimensions along which a user needs to search.

Early Filtering Is a Universal Design Pattern

Database optimization often rewards filtering early. If a query can eliminate irrelevant rows before sorting, grouping, joining, or calculating derived values, it avoids paying for work that will later be discarded.

This is a general law of systems: do cheap, decisive narrowing before expensive interpretation.

A team reviewing a large codebase can apply the same law to human reasoning. Before reading every line of a module, ask what the function promises. Before tracing every call, inspect the summary and signature. Before studying an exception path, identify the normal result. Before opening a complex query plan, check whether the predicate is direct and whether the result set is unnecessarily large.

The opposite pattern creates waste. A query retrieves millions of rows, sorts them, computes several expressions, and only then applies a restriction that could have been expressed at the beginning. A reader encounters a long narrative about implementation history, edge cases, and internal details before learning the basic purpose of the function.

In both cases, the system is making the consumer perform work that the producer could have prevented.

This provides a useful review question for almost any technical artifact:

What can be made explicit earlier so that irrelevant work is never performed?

For SQL, the answer might be an appropriate index, a narrower projection, a direct predicate, or a limit on results. For documentation, it might be a precise summary, a clear return description, or a direct statement of side effects. For an API, it might be a name that distinguishes retrieval from mutation. For a log message, it might be a field that identifies the request before the details begin.

The deeper pattern is progressive disclosure. Reveal the smallest useful answer first. Preserve access to depth without forcing depth on everyone.

When Optimization Becomes Obscurity

There is a danger in taking this principle too literally. The shortest path is not always the best path. A query can be made technically efficient while becoming so opaque that future maintainers cannot verify its behavior. A docstring can be compressed into a clever one liner that omits a crucial constraint.

This is where machine search and human understanding diverge. A database optimizer cares about execution cost under a formal model. A human reader cares about meaning, consequences, and trust. The best software design must serve both.

A useful distinction is between compression and elision. Compression expresses the same useful meaning in less space. Elision removes information that someone may need. A summary line compresses a function's purpose. A vague phrase such as "process data" elides the very distinction a reader is searching for.

The same distinction appears in SQL. Rewriting a predicate so an index can use it is beneficial compression of the search operation. Removing a necessary condition merely to make the query faster is not optimization. It is a change in meaning.

The goal, then, is not minimal text or minimal computation in isolation. It is minimal unnecessary work while preserving inspectable meaning.

That last phrase is important. Systems need to be not only fast, but also explainable enough to maintain. A query that returns quickly but cannot be safely modified is carrying hidden costs. A terse docstring that saves a few seconds now but causes repeated misunderstandings later is not truly efficient.

We can model this with a simple equation:

Total cost = execution cost + interpretation cost + correction cost

Indexes reduce execution cost. Clear predicates reduce both execution and interpretation cost. Precise docstrings reduce interpretation cost. Accurate documentation and explicit contracts reduce correction cost when assumptions change.

The most valuable improvements reduce more than one term at once.

A Practical Method for Searchable Software

The combined lesson can become a concrete design method. Whenever you create a query, function, module, or API, ask four questions.

1. What is the first question a user will ask?

For a query, it may be, "Which records match this condition?" For a function, it may be, "What does this return?" Put the answer in the most accessible form available. Use a direct predicate. Start the docstring with a summary line. Choose names that expose the primary operation.

2. Can the answer be reached without transforming the evidence?

Avoid wrapping an indexed column in unnecessary arithmetic or functions. Avoid forcing a reader to infer purpose from implementation details. Directness is valuable because every transformation creates another place for assumptions to hide.

3. What work can be postponed until relevance is established?

Limit result sets before expensive operations. Filter before sorting or grouping when the logic permits it. In documentation, keep secondary history and edge cases after the core contract. In code review, inspect the public behavior before exploring internal machinery.

4. What information must remain visible for safe use?

State constraints, side effects, return meanings, and important exceptions. A system that is easy to search but difficult to trust is only partially optimized.

This method also suggests how to improve an existing codebase. Do not begin by rewriting everything. Find the places where retrieval is most expensive. Which queries scan too much? Which functions require repeated explanation? Which names cause developers to open the implementation every time? These are the software equivalent of missing or unusable indexes.

Fix the access path first. Add or revise indexes where they address real search patterns. Rewrite predicates to remain usable by the database. Add concise, accurate summaries to frequently reused functions. Then measure whether both machine performance and human navigation improve.

Key Takeaways

  • Treat every interface as a search surface. A query, function name, signature, and docstring should help the next user reach the relevant answer directly.
  • Lead with the highest value information. Put purpose in the first sentence and decisive filters as early as correctness allows.
  • Prefer direct expressions. Avoid unnecessary transformations around indexed fields and avoid forcing readers to infer a contract from implementation details.
  • Use layers instead of overload. Give a concise summary first, then provide details about inputs, outputs, errors, side effects, and edge cases.
  • Optimize for total cost. Consider execution time, interpretation effort, and the future cost of misunderstanding, not just the fastest immediate result.

The most mature software is not merely software that runs quickly. It is software that lets the right question reach the right answer with little wasted motion, whether the search is performed by a database engine or by a tired developer at the end of a long debugging session.

That reframes optimization. It is not fundamentally about making systems do less. It is about helping them avoid doing irrelevant work while keeping the important meaning visible. An index is a promise that useful data can be found directly. A good docstring is the same promise made to a human.

The best code keeps both promises.

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 🐣