A logbook for curious waters
← Software Engineering Field Guide

Introduce Assertion

Before you begin: Conditions, invariants, and the difference between a programming defect and invalid input.

An assertion states a condition the programmer believes must already be true at a particular point. Introduce Assertion turns an implicit internal assumption into an explicit check. A failed assertion indicates a programming mistake or violated internal contract, not an ordinary user mistake to recover from. 1

Make an internal ordering assumption visible

Suppose earlier code sorts two endpoints before passing them to an internal width calculation. The calculation assumes the end is not before the start. Without an assertion, a defect in that earlier step could quietly produce a negative width.

public static class Ranges
{
    public static int Width(int start, int end)
    {
        System.Diagnostics.Debug.Assert(
            end >= start, "Endpoints should already be ordered.");
        return end - start;
    }
}
Console.WriteLine(Ranges.Width(3, 8)); // 5

Debug.Assert documents and checks the assumption in builds where the DEBUG conditional symbol enables the call. It is not a reliable runtime validation boundary, and its failure handling is not equivalent to throwing a normal argument exception. This example’s automated C# execution checks valid widths; it does not claim that a Release build rejects reversed endpoints. 2

def width(start, end):
    assert end >= start, "Endpoints should already be ordered."
    return end - start
print(width(3, 8))  # 5

With assertions enabled, reversed endpoints raise AssertionError at the point where the assumption is violated. Python’s optimization option can remove assertion statements, so callers must not rely on this assertion to validate untrusted input. 3

Assertions must not perform required work

An assertion expression should inspect state, not change it. Placing a database write, increment, or necessary function call inside an assertion can make program behavior depend on whether assertions are enabled.

For public input, write an ordinary validation branch and return or raise the documented error. For security checks, use enforced authorization logic. “The user should never submit this” is not an internal invariant.

Assertions also do not prove that a condition always holds. They expose violations only when execution reaches the check in a configuration that runs it. Combine them with tests and a design that makes invalid states difficult to construct.

The benefit is a precise statement of programmer intent: this value is expected to be ordered already. The difference between checking an established invariant and establishing validity is what makes an assertion useful rather than misleading.

Sources

  1. Martin Fowler — Introduce Assertion.
  2. Microsoft — Debug.Assert.
  3. Python — The assert statement.