Programming Search⌘K

Techniquecore

Introduce assertion

When code works only if some condition is true, state that condition with an assertion, so that readers see it and a programming error fails at once; not for checking input from outside.

Family
refactoring
Intent
Make an assumption of the code explicit, and make it fail loudly when a programmer breaks it.

Purpose

Code often works only when some condition holds: a rate is not negative, a list is sorted, a value is in range. If the condition is not written down, a reader must find it from the code, and a caller that breaks it gets a wrong result, not an error.

Introduce assertion writes the condition as an assertion. The catalogue card adds an assertion that a discount rate is not negative before the line that uses it.1 The first edition has the refactoring under the same name.2 The book gives two reasons: the assertion tells the reader what the code assumes, and it helps debugging, because a broken assumption fails where it is broken.3

An assertion is for a condition that must always be true if the program is correct. The book's test: the program must behave the same if all the assertions are removed.3 So assertions are not a way to check data from users, files or other systems. For those, use ordinary checks that report an error. See exception handling, and assertions for the language feature.

Steps

  1. When you see that the code assumes a condition is true, add an assertion that states it.3
  2. Test.

Because an assertion does not change what a correct program does, adding one is a refactoring: a test that passed before still passes.

Example

A refund function assumes that the days used are between zero and the days paid for. A caller with a bug passes more days used than paid for, and the function returns a negative refund. With the assertion, the bug fails at once, with a message that names the broken assumption.

import assert from "node:assert/strict";

function refundCents(paidCents, daysPaid, daysUsed) {
  assert.ok(daysUsed >= 0 && daysUsed <= daysPaid, "days used must be between 0 and days paid");
  return Math.round((paidCents * (daysPaid - daysUsed)) / daysPaid);
}

assert.equal(refundCents(3000, 30, 10), 2000);
assert.equal(refundCents(3000, 30, 30), 0);
assert.throws(() => refundCents(3000, 30, 31), /between 0 and days paid/);
console.log("introduce assertion: tests pass");
Output
introduce assertion: tests pass

Without the assertion, refundCents(3000, 30, 31) returns -100, and the error shows up much later, as a strange charge.

Language What the example shows
JavaScript an assertion with node:assert, as above
Python the assert statement, and the fact that python -O removes it, which is why it must not check user input
Java the assert statement, which runs only when assertions are enabled, and a test that shows whether they are
Go Go has no assertions; the example states the assumption with a check that panics, as a programming error
PythonGitHub
import subprocess
import sys


def refund_cents(paid_cents: int, days_paid: int, days_used: int) -> int:
    assert 0 <= days_used <= days_paid, "days used must be between 0 and days paid"
    return round(paid_cents * (days_paid - days_used) / days_paid)


assert refund_cents(3000, 30, 10) == 2000
try:
    refund_cents(3000, 30, 31)
    raise RuntimeError("expected AssertionError")
except AssertionError as e:
    assert "between 0" in str(e)

# With -O, the assert statement is gone, and the bug returns a negative refund.
code = "assert False, 'gone'\nprint('no assert')"
out = subprocess.run([sys.executable, "-O", "-c", code], capture_output=True, text=True)
assert out.stdout.strip() == "no assert"
print("introduce assertion: tests pass")
Output
introduce assertion: tests pass
JavaGitHub
public class Main {
    static long refundCents(long paidCents, int daysPaid, int daysUsed) {
        assert daysUsed >= 0 && daysUsed <= daysPaid : "days used must be between 0 and days paid";
        return Math.round((double) paidCents * (daysPaid - daysUsed) / daysPaid);
    }

    public static void main(String[] args) {
        boolean enabled = false;
        assert enabled = true; // the assignment runs only when assertions are enabled
        System.out.println("assertions enabled: " + enabled);

        if (refundCents(3000, 30, 10) != 2000) throw new IllegalStateException("refund");
        if (!enabled) {
            // Without assertions, the broken assumption is not caught.
            if (refundCents(3000, 30, 31) != -100) throw new IllegalStateException("expected -100");
        }
        System.out.println("introduce assertion: tests pass");
    }
}
Output
assertions enabled: false
introduce assertion: tests pass
package main

import (
	"fmt"
	"math"
)

// refundCents panics if daysUsed is out of range: that is a bug in the
// caller, not an input error. Input from users is checked before this.
func refundCents(paidCents, daysPaid, daysUsed int) int {
	if daysUsed < 0 || daysUsed > daysPaid {
		panic(fmt.Sprintf("days used %d must be between 0 and days paid %d", daysUsed, daysPaid))
	}
	return int(math.Round(float64(paidCents*(daysPaid-daysUsed)) / float64(daysPaid)))
}

func main() {
	if refundCents(3000, 30, 10) != 2000 {
		panic("refund")
	}
	func() {
		defer func() {
			if recover() == nil {
				panic("expected a panic")
			}
		}()
		refundCents(3000, 30, 31)
	}()
	fmt.Println("introduce assertion: tests pass")
}
Output
introduce assertion: tests pass

When to use

  • The code assumes something. A condition that a reader would need to know to use the code correctly.3
  • A comment states an assumption. A comment that says that a rate is never negative can become an assertion that the code checks.
  • After a refactoring that relies on a condition. In Replace Derived Variable with Query, an assertion checks that a stored value and a computed value agree before the stored one goes.

Pitfalls

Assertions can be turned off. In Python, "The current code generator emits no code for an assert statement when optimization is requested at compile time."4 In Java, an assert statement is enabled "if and only if the host system has determined that the top level class or interface that lexically contains the assert statement enables assertions".5 Code that must run, and checks of outside data, must not be in an assertion.

Side effects in the condition. If the asserted expression changes state, the program behaves differently when assertions are off. Keep the condition free of side effects.

Too many assertions. An assertion for each line hides the ones that matter. Assert only a condition that must be true for the code to work.3

Go. The Go FAQ explains that Go has no assertions, because "programmers use them as a crutch to avoid thinking about proper error handling and reporting".6 In Go, return an error for conditions that can happen, and panic only for a programming error.

Tools that do it

This refactoring is a sequence of steps, not one action of a tool. See assertions for the assertion features of each language, and for contracts.

References

  1. Martin Fowler, Catalog of Refactorings, Introduce Assertion, the entry
  2. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 9, Simplifying Conditional Expressions, Introduce Assertion
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 10, Simplifying Conditional Logic, Introduce Assertion, motivation and mechanics
  4. The Python Language Reference, Simple statements, 7.3 The assert statement
  5. The Java Language Specification, Java SE 21 Edition, Chapter 14, 14.10 The assert Statement
  6. The Go Programming Language, Frequently Asked Questions, Why does Go not have assertions?

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/A6QN08/text.yaml