Conceptcore
Assertion
Also called assert, design by contract, precondition, postcondition, class invariant, contract.
An assertion states a condition that must be true at a point in a program. A false assertion at run time shows a bug. Contracts use assertions as preconditions, postconditions and invariants.
- Applies to
- core-languages
Idea
A programmer who writes a function makes assumptions. The argument is not negative. The list is sorted. The balance is never below zero. Most of these assumptions stay in the head of the programmer. An assertion writes one of them into the program as a Boolean expression. When the program runs, it can test the expression. If the expression is false, the assumption was wrong, and the program has a bug.
Bertrand Meyer put it this way: "any runtime violation of an assertion is not a special case but always the manifestation of a software bug."1 This is the difference between an assertion and an ordinary check. An ordinary check handles a case that can happen, such as a file that is missing. An assertion states a case that must not happen.
In Python, assert raises AssertionError when its condition is false.
def isqrt(n):
assert n >= 0, "precondition: n >= 0"
r = 0
while (r + 1) * (r + 1) <= n:
r += 1
assert r * r <= n < (r + 1) * (r + 1), "postcondition"
return r
print([isqrt(n) for n in [0, 1, 15, 16]])
try:
isqrt(-4)
except AssertionError as exc:
print("AssertionError:", exc)
[0, 1, 3, 4]
AssertionError: precondition: n >= 0
The first assertion states what the caller must give. The second states what the function promises in return. The two together are a small contract.
How it works
At the level of the machine, an assertion is a comparison and a branch. When the condition holds, the program goes on. When it does not, the program jumps to a failure routine. The languages differ in what that routine does.
| Language | Assertion | On failure | How it is removed |
|---|---|---|---|
| Python | assert cond, msg |
raises AssertionError |
the option -O23 |
| Java | assert cond : msg; |
throws AssertionError |
disabled unless the launcher gets -ea45 |
| C | assert(cond) |
writes a report to standard error, calls abort |
define NDEBUG before <assert.h>6 |
| C++ | assert(cond) from <cassert> |
as in C | NDEBUG, as in C7 |
| C# | Debug.Assert(cond, msg) |
writes a message and shows the call stack | dropped when the symbol DEBUG is not defined89 |
| Rust | assert!(cond, msg) |
panics | never removed10 |
| Rust | debug_assert!(cond, msg) |
panics | not run in optimized builds by default11 |
| JavaScript | assert.ok(value, msg) from node:assert |
throws AssertionError |
never removed12 |
Removal in release builds
Many languages let a build turn the assertions off. The reason is cost: a check that walks a whole data structure can be slower than the work it checks. The ways to turn them off differ.
- The preprocessor. In C, if
NDEBUGis defined where<assert.h>is included,assertis defined as((void)0).6 The expression is gone before the compiler sees it. - The compiler. In Python,
assertis the same asif __debug__: if not expression: raise AssertionError. With-O,__debug__isFalseand the compiler emits no code forassert.2 In C#,Debug.Assertcarries the attributeConditional("DEBUG").8 A call to a method with this attribute is not compiled unless the symbol is defined.9 - The runtime. In Java, an assertion is enabled or disabled per class, and a disabled
assert"does nothing". It does not evaluate its expressions.4 Assertions are disabled by default, and the launcher option-eaenables them.5 - The build profile. Rust keeps
assert!in every build, and the documentation says that it cannot be disabled.10debug_assert!is the version for checks that are too expensive for a release build. An optimized build does not run it unless the compiler gets-C debug-assertions.11
The JLS describes the usual practice: assertion checking is enabled during development and testing, and disabled for deployment, to improve performance.4 The cost of this practice is that the deployed program does not check the conditions that the tests checked. The pitfalls below show what can go wrong.
Static assertions
A static assertion is checked by the compiler, not at run time. C has static_assert(constant-expression, string-literal). If the expression is zero, the compiler must produce a diagnostic, which should include the text of the string literal.6 A static assertion costs nothing at run time, but it can only test what the compiler knows, such as the size of a type.
Design by contract
Meyer built a method of software construction on assertions and named it Design by Contract. Its primary source is his 1992 article in IEEE Computer, which uses the language Eiffel.1 A routine and its caller are two parties to a contract. The caller is the client, and the routine is the supplier.1
Eiffel attaches the assertions to the routine. The clause require holds the precondition, and the clause ensure holds the postcondition. In the postcondition, old child_count means the value of child_count on entry to the call.1 A missing precondition is the same as require True, the assertion that every state satisfies.1
- A precondition is a requirement that each call must satisfy to be correct. It is an obligation of the client.1
- A postcondition is a property that the routine ensures in return. It is an obligation of the supplier.1
- A class invariant is a property of every instance of a class. Each creation procedure must give an object that satisfies it, and each exported routine must keep it true. In effect, the invariant is added to the precondition and the postcondition of each exported routine. It need not hold in the middle of a routine, only in the states that a client can observe.1
The contract says who has a bug when an assertion fails. "A precondition violation indicates a bug in the client (caller)." "A postcondition violation is a bug in the supplier (routine)."1
Who should check
A precondition moves a check to the caller. The routine does not test its own precondition. Meyer calls this "an absolute rule": a condition is either in the require clause or in an if in the body, "but never in both".1 He calls this "the exact opposite of the idea of defensive programming", where each party checks everything.1 Gray's fail-fast modules take the other view and are made fail-fast "by defensive programming": they check their inputs, intermediate results, outputs and data structures, and stop when a check fails.13 The two views agree that a failed check is a fault. They differ in where the check belongs.
Meyer says that there is "no absolute rule" for how strong a precondition should be. A "demanding" contract has a strong precondition and puts the work on the clients. A "tolerant" one has a weak precondition and puts the work on the routine. Meyer calls the choice "a pragmatic decision about division of labor", and says that "the best solution is the one that achieves the simplest architecture."1
Monitoring
In Eiffel, the developer chooses per class how many assertions the program checks at run time: none, preconditions only, preconditions and postconditions, those plus class invariants, or all assertions. Preconditions only is the default. A violation of a monitored assertion raises an exception.1 Meyer describes monitoring as "a way to call the developer's bluff", because it checks what the software does against what its author thinks it does.1
Contracts and inheritance
A subclass can redeclare a routine. Meyer's rule is that the new version may weaken the precondition and strengthen the postcondition, but not the reverse. Eiffel writes require else and ensure then in a redeclaration, so the new precondition is the old one or the new one, and the new postcondition is the old one and the new one. The invariant of a class includes the invariants of all its parents, so it is always stronger than or equal to each of them.1
Contracts without contract syntax
Most of the tier 1 languages have no require or ensure. Programs write the contract with the tools that exist. The example files use an account with a withdraw method:
- The precondition
0 < amount <= balanceis anassertat the start of the method in Python, an exception in Java and C#, and a returned error in Go and Rust. - The postcondition
balance == old - amountkeeps a copy of the old value in a local variable, because these languages have noold. - The invariant
balance >= 0is a private method that each public method calls before it returns. In Rust, the typeu32makes a negative balance impossible, so the invariant needs no check.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Native | |
| C | Standard library | |
| C# | Standard library | |
| JavaScript | Standard library | |
| TypeScript | Idiom | |
| Go | Absent | |
| Rust | Native | |
| Kotlin | Standard library | The standard functions require and check throw IllegalArgumentException and IllegalStateException when a condition is false; no example file because kotlinc is not installed on the machine that recorded the examples. Alternative: Require for a precondition on an argument, check for the state of an object. |
| SQL | Idiom | A CHECK constraint states a Boolean condition that each row must satisfy, and the database raises an error for a row that violates it. Alternative: UNIQUE, EXCLUDE or FOREIGN KEY constraints for conditions across rows or tables. |
| Bash | Absent | The shell has no assertion command. Alternative: A test such as [[ expression ]] followed by || exit with a status. |
| PowerShell | Absent | The language has no assertion statement; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: An if statement that throws when the condition is false. |
| HTML | Does not apply | Markup does not run code. |
| CSS | Does not apply | Style rules do not run code. |
| Regular expressions | Does not apply | A pattern states no conditions on a program; a lookahead assertion is a different idea. |
| Language | Verdict | Form |
|---|---|---|
| Python | native | the statement assert; removed by -O |
| JavaScript | stdlib | the module node:assert in Node.js; console.assert only logs |
| TypeScript | idiom | assertion functions with the return type asserts condition |
| Java | native | the statement assert; disabled unless -ea |
| C | stdlib | the macro assert and NDEBUG; the keyword static_assert |
| C++ | stdlib | assert from <cassert>; the declaration static_assert |
| C# | stdlib | Debug.Assert, compiled only with DEBUG; Trace.Assert |
| Go | absent | no assertions; an if that returns an error or panics |
| Rust | native | assert! in every build, debug_assert! in builds without optimization |
| Kotlin | stdlib | require and check throw exceptions |
| PowerShell | absent | no assertion statement; a script throws when a check fails |
| Bash | absent | no assertion command; a test followed by exit |
| SQL | idiom | a CHECK constraint states a Boolean condition that each row must satisfy |
| Regex | n/a | a pattern has no assertions in this sense; a lookahead is a different idea |
| HTML/CSS | n/a | markup and style rules state no conditions on a program |
Three groups stand out.
- A statement in the language. Python and Java have the keyword
assert. Both can turn it off, Python at compile time and Java per class at run time.24 Java added the statement through JSR 41, "A Simple Assertion Facility", whose final release was on 9 May 2002.14 - A library function or macro. C and C++ use a macro, C# a method with a conditional attribute, Rust a macro, and Node.js a module.681012 Kotlin has the functions
require, which throwsIllegalArgumentException, andcheck, which throwsIllegalStateException.15 - No assertions on purpose. The Go FAQ says that Go does not provide assertions. The designers' experience was that programmers use them "as a crutch to avoid thinking about proper error handling and reporting".16 A Go program writes an
ifstatement and returns an error for a bad argument, or panics for a broken invariant.
TypeScript adds a type-level form. A function whose return type is asserts condition tells the checker that the condition is true after the call returns. A return type asserts value is string narrows the type of value.17 The checker trusts the signature and does not check the body (see the TypeScript example).
SQL states conditions on data. A CHECK constraint requires that the value in a column satisfy a Boolean expression, and the database rejects a row that does not.18
class Account:
def __init__(self, balance):
self.balance = balance
self._invariant()
def _invariant(self):
assert self.balance >= 0, f"invariant: balance is {self.balance}"
def withdraw(self, amount):
assert 0 < amount <= self.balance, f"precondition: withdraw {amount} from {self.balance}"
old = self.balance
self.balance -= amount
assert self.balance == old - amount, "postcondition"
self._invariant()
account = Account(100)
account.withdraw(30)
print("balance", account.balance)
try:
account.withdraw(500)
except AssertionError as exc:
print("AssertionError:", exc)
print("balance", account.balance)
print("__debug__ is", __debug__)
balance 70
AssertionError: precondition: withdraw 500 from 70
balance 70
__debug__ is True
- Verdict: native.
assert expression, messageraisesAssertionErrorwith the message when the expression is false. - The statement is the same as
if __debug__: if not expression: raise AssertionError(message). With the option-O,__debug__isFalseand the compiler emits no code forassert. - Python has no syntax for preconditions, postconditions or invariants. The example writes them as
assertstatements at the start and the end of each method.
With -O, the same program has no checks. The withdrawal of 500 goes through, and the invariant is broken without a report.
This code runs but gives a wrong answer on purpose.
class Account:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
assert 0 < amount <= self.balance, "precondition"
self.balance -= amount
account = Account(100)
account.withdraw(500)
print("balance", account.balance)
print("__debug__ is", __debug__)
balance -400
__debug__ is False
An assertion with parentheses around the condition and the message tests a tuple. A tuple that is not empty is true, so the assertion never fails. The compiler warns about it on standard error.
This code runs but gives a wrong answer on purpose.
balance = -5
assert (balance >= 0, "balance must not be negative")
print("passed with balance", balance)
passed with balance -5
#include <cassert>
#include <iostream>
#include <stdexcept>
class Account {
public:
explicit Account(int balance) : balance_(balance) { assert(invariant()); }
void withdraw(int amount) {
if (amount <= 0 || amount > balance_) {
throw std::invalid_argument("cannot withdraw " + std::to_string(amount));
}
const int old = balance_;
balance_ -= amount;
assert(balance_ == old - amount && "postcondition");
assert(invariant());
}
int balance() const { return balance_; }
private:
bool invariant() const { return balance_ >= 0; }
int balance_;
};
static_assert(sizeof(int) >= 4, "int has at least 32 bits");
int main() {
Account account(100);
account.withdraw(30);
std::cout << "balance " << account.balance() << '\n';
try {
account.withdraw(500);
} catch (const std::invalid_argument& e) {
std::cout << "rejected: " << e.what() << '\n';
}
}
balance 70
rejected: cannot withdraw 500
- Verdict: stdlib. C++ takes
assertfrom C through<cassert>, with the same rule forNDEBUG.static_assertis a declaration that the compiler checks. assert(condition && "text")puts a message in the report. A string literal converts totrue, so it does not change the test.- In the standard library, a precondition is part of the specification of a function, and a call that violates it has undefined behaviour. The library does not promise to check it.
A failed assert writes a report to standard error and calls abort.
This code fails on purpose. The output below is the error.
#include <cassert>
#include <iostream>
int average(const int* values, int count) {
assert(count > 0 && "precondition: no values");
int sum = 0;
for (int i = 0; i < count; ++i) {
sum += values[i];
}
return sum / count;
}
int main() {
int values[] = {2, 4};
std::cout << average(values, 2) << '\n';
std::cout << average(values, 0) << '\n';
}
public class Main {
static final class Account {
private int balance;
Account(int balance) {
if (balance < 0) {
throw new IllegalArgumentException("negative opening balance " + balance);
}
this.balance = balance;
}
void withdraw(int amount) {
if (amount <= 0 || amount > balance) {
throw new IllegalArgumentException("cannot withdraw " + amount + " from " + balance);
}
int old = balance;
balance -= amount;
assert balance == old - amount : "postcondition";
assert balance >= 0 : "invariant: balance is " + balance;
}
}
public static void main(String[] args) {
boolean enabled = false;
assert enabled = true;
System.out.println("assertions enabled: " + enabled);
Account account = new Account(100);
account.withdraw(30);
System.out.println("balance " + account.balance);
try {
account.withdraw(500);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
assertions enabled: false
balance 70
rejected: cannot withdraw 500 from 70
- Verdict: native.
assert condition : message;throwsAssertionErrorwith the message when assertions are enabled and the condition is false. - Assertions are disabled by default. The option
-eaof thejavalauncher enables them. A disabledassertdoes not evaluate its expressions. The lineassert enabled = true;uses this to report the state. - The JLS says that assertions should not check the arguments of public methods, because the check must hold whether assertions are enabled or not. The example checks the arguments with
ifandIllegalArgumentException, and usesassertfor the postcondition and the invariant.
The launcher option -ea is one way to enable assertions. A program can also set the default assertion status of a class loader. The setting applies to the classes that the loader initializes after the call, here Ledger. A failed assert in Ledger then throws AssertionError.
This code raises AssertionError, on purpose.
public class Main {
public static void main(String[] args) {
ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
Ledger.withdraw(500);
System.out.println("balance " + Ledger.balance);
}
}
class Ledger {
static int balance = 100;
static void withdraw(int amount) {
balance -= amount;
assert balance >= 0 : "invariant: balance is " + balance;
}
}
#include <assert.h>
#include <stdio.h>
struct account {
int balance;
};
static_assert(sizeof(int) >= 2, "int has at least 16 bits");
static void withdraw(struct account *a, int amount) {
assert(a != NULL);
assert(amount > 0 && amount <= a->balance);
int old = a->balance;
a->balance -= amount;
assert(a->balance == old - amount);
assert(a->balance >= 0);
}
int main(void) {
struct account a = {100};
withdraw(&a, 30);
printf("balance %d\n", a.balance);
#ifdef NDEBUG
puts("NDEBUG is defined");
#else
puts("NDEBUG is not defined");
#endif
}
balance 70
NDEBUG is not defined
- Verdict: stdlib. The macro
assertin<assert.h>writes the failed expression, the file, the line and the function to standard error, then callsabort. - If
NDEBUGis defined where<assert.h>is included,assertexpands to((void)0). The expression is not evaluated. static_assertis checked by the compiler. It costs nothing at run time.
A precondition that fails stops the program.
This code fails on purpose. The output below is the error.
#include <assert.h>
#include <stdio.h>
struct account {
int balance;
};
static void withdraw(struct account *a, int amount) {
assert(amount > 0 && amount <= a->balance);
a->balance -= amount;
}
int main(void) {
struct account a = {100};
withdraw(&a, 500);
printf("balance %d\n", a.balance);
}
With -DNDEBUG, the same program runs on with a negative balance.
This code runs but gives a wrong answer on purpose.
#include <assert.h>
#include <stdio.h>
struct account {
int balance;
};
static void withdraw(struct account *a, int amount) {
assert(amount > 0 && amount <= a->balance);
a->balance -= amount;
}
int main(void) {
struct account a = {100};
withdraw(&a, 500);
printf("balance %d\n", a.balance);
}
balance -400
A compile-time assertion that is false stops the build.
This code does not compile, on purpose.
#include <assert.h>
struct header {
char tag;
int length;
};
static_assert(sizeof(struct header) == 5, "header is 5 bytes");
int main(void) { return 0; }
using System;
using System.Diagnostics;
var account = new Account(100);
account.Withdraw(30);
Console.WriteLine($"balance {account.Balance}");
try
{
account.Withdraw(500);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine($"rejected: {e.ParamName} = {e.ActualValue}");
}
#if DEBUG
Console.WriteLine("DEBUG is defined");
#else
Console.WriteLine("DEBUG is not defined");
#endif
class Account(int balance)
{
public int Balance { get; private set; } = balance;
public void Withdraw(int amount)
{
if (amount <= 0 || amount > Balance)
{
throw new ArgumentOutOfRangeException(nameof(amount), amount, "cannot withdraw");
}
int old = Balance;
Balance -= amount;
Debug.Assert(Balance == old - amount, "postcondition");
Debug.Assert(Balance >= 0, "invariant");
}
}
balance 70
rejected: amount = 500
DEBUG is defined
- Verdict: stdlib.
Debug.Assertchecks a condition and reports a failure. It carries[Conditional("DEBUG")], so the compiler drops each call when the symbolDEBUGis not defined. Trace.Assertis the version that stays in release builds.- The public method checks its argument with an exception, which runs in every build.
Debug.Assertchecks the postcondition and the invariant.
import assert from "node:assert/strict";
class Account {
#balance;
constructor(balance) {
assert.ok(Number.isInteger(balance) && balance >= 0, "precondition: balance");
this.#balance = balance;
}
get balance() {
return this.#balance;
}
withdraw(amount) {
assert.ok(amount > 0 && amount <= this.#balance, `precondition: withdraw ${amount} from ${this.#balance}`);
const old = this.#balance;
this.#balance -= amount;
assert.equal(this.#balance, old - amount, "postcondition");
}
}
const account = new Account(100);
account.withdraw(30);
console.log("balance", account.balance);
try {
account.withdraw(500);
} catch (err) {
console.log(err.name, err.code, err.message);
}
balance 70
AssertionError ERR_ASSERTION precondition: withdraw 500 from 70
- Verdict: stdlib. The Node.js module
node:assertthrows anAssertionErrorwhen a check fails.assert.ok(value, message)tests that the value is truthy. - The language has no
assertstatement and no flag that removes checks. A check runs in every build. console.assertis not the same. It only writes a message, and the program goes on.
console.assert writes "Assertion failed" to standard error and does not throw. The withdrawal below goes through.
This code runs but gives a wrong answer on purpose.
let balance = 100;
function withdraw(amount) {
console.assert(amount <= balance, "precondition: withdraw", amount, "from", balance);
balance -= amount;
}
withdraw(500);
console.log("balance", balance);
balance -400
function assert(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new Error("assertion failed: " + message);
}
}
function assertIsString(value: unknown): asserts value is string {
assert(typeof value === "string", `expected a string, got ${typeof value}`);
}
function shout(value: unknown): string {
assertIsString(value);
return value.toUpperCase();
}
console.log(shout("ok"));
try {
console.log(shout(42));
} catch (err) {
console.log((err as Error).message);
}
OK
assertion failed: expected a string, got number
- Verdict: idiom. TypeScript adds no run-time check. The program uses an ordinary function that throws, or the module
node:assert. - The return type
asserts conditiontells the checker that the condition is true after the call returns.asserts value is stringnarrows the type ofvalue, sovalue.toUpperCase()type checks. - The checker trusts the signature and does not check the body. The block below shows the result of a body that does not throw.
This assertion function only logs. The checker still narrows value to string after the call, and the program fails when it calls a string method on a number.
This code raises TypeError, on purpose.
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== "string") {
console.log("not a string:", typeof value);
}
}
function shout(value: unknown): string {
assertIsString(value);
return value.toUpperCase();
}
console.log(shout(42));
package main
import (
"errors"
"fmt"
)
type Account struct {
balance int
}
var ErrInsufficient = errors.New("insufficient funds")
func (a *Account) invariant() {
if a.balance < 0 {
panic(fmt.Sprintf("invariant: balance is %d", a.balance))
}
}
func (a *Account) Withdraw(amount int) error {
if amount <= 0 {
return fmt.Errorf("withdraw %d: amount must be positive", amount)
}
if amount > a.balance {
return fmt.Errorf("withdraw %d from %d: %w", amount, a.balance, ErrInsufficient)
}
old := a.balance
a.balance -= amount
if a.balance != old-amount {
panic("postcondition: balance not reduced by amount")
}
a.invariant()
return nil
}
func main() {
a := &Account{balance: 100}
fmt.Println(a.Withdraw(30), a.balance)
err := a.Withdraw(500)
fmt.Println(err, errors.Is(err, ErrInsufficient), a.balance)
}
<nil> 70
withdraw 500 from 70: insufficient funds true 70
- Verdict: absent. Go has no
assert. The Go FAQ says that programmers use assertions "as a crutch to avoid thinking about proper error handling and reporting". - A bad argument from a caller is an expected failure, so
Withdrawreturns an error. A broken invariant is a bug inAccountitself, so the check panics. - The checks are ordinary
ifstatements. They run in every build, and no flag removes them.
struct Account {
balance: u32,
}
impl Account {
fn withdraw(&mut self, amount: u32) -> Result<(), String> {
if amount == 0 || amount > self.balance {
return Err(format!("cannot withdraw {amount} from {}", self.balance));
}
let old = self.balance;
self.balance -= amount;
debug_assert_eq!(self.balance, old - amount, "postcondition");
Ok(())
}
}
const _: () = assert!(u32::BITS == 32);
fn main() {
let mut account = Account { balance: 100 };
println!("{:?} {}", account.withdraw(30), account.balance);
println!("{:?} {}", account.withdraw(500), account.balance);
println!("debug assertions: {}", cfg!(debug_assertions));
}
Ok(()) 70
Err("cannot withdraw 500 from 70") 70
debug assertions: true
- Verdict: native.
assert!panics when its condition is false, in every build.assert_eq!andassert_ne!compare two values and print both on failure. debug_assert!anddebug_assert_eq!run only in builds without optimization, unless the compiler gets-C debug-assertions. The expression is still type checked in every build.assert!in aconstitem runs when the compiler evaluates the constant. The last block below shows a false one.- The type
u32cannot hold a negative balance, so the invariant "balance is not negative" is part of the type and needs no assertion.
A failed assert! panics. The default hook prints the message, and the program exits with status 101.
This code panics, on purpose.
fn average(values: &[u32]) -> u32 {
assert!(!values.is_empty(), "precondition: no values");
values.iter().sum::<u32>() / values.len() as u32
}
fn main() {
println!("{}", average(&[2, 4]));
println!("{}", average(&[]));
}
In a const item, the compiler evaluates the assertion, and a false one stops the build.
This code does not compile, on purpose.
struct Header {
tag: u8,
length: u32,
}
const _: () = assert!(std::mem::size_of::<Header>() == 5, "Header is 5 bytes");
fn main() {
let h = Header { tag: 1, length: 2 };
println!("{} {}", h.tag, h.length);
}
Variations and related ideas
- Assertions in tests. A unit test calls code and asserts facts about the result. A failed test assertion reports a failed test, not a bug in production (Unit testing).
- Assertions as panics. In Rust and C, a failed assertion is a panic or an abort (Panic). In Python and Java, it is an exception that a handler can catch. The JLS says that
AssertionErroris intended never to be caught.4 - Rescue and retry. Eiffel has a
rescueclause. When a routine fails, the clause can restore a consistent state and executeretryto try again, or end withoutretry, and then the routine fails and its caller gets an exception. Meyer calls the second case "organized panic".1 - Types in place of assertions. A type can make a bad state impossible. A non-nullable reference removes the need to assert that a pointer is not null (Null reference). An unsigned integer removes the assertion that a count is not negative.
- Library preconditions in C++. The C++ standard library specifies preconditions for its functions. A call that violates a precondition has undefined behaviour.19 The library does not promise to check it.
Pitfalls
Side effects in an assertion
When assertions are removed, their expressions are not evaluated. Code that does work inside an assertion stops doing that work in a release build. The JLS says that the expressions in assertions "should generally be free of side effects".4 Here the call to pop is inside the assert. With -O, the call disappears, and the queue keeps its first item.
This code runs but gives a wrong answer on purpose.
queue = ["job-1", "job-2"]
assert queue.pop(0) == "job-1", "unexpected first job"
print("next job:", queue[0])
next job: job-1
The fix is to do the work in a statement of its own and to assert only on the result.
Assertions that check input
A user, a file or a network can send bad input at any time. Such input is an expected failure, not a bug, so the program must check it in every build. The JLS says that assertions should not check the arguments of public methods, because that check is part of the contract of the method and must hold whether assertions are enabled or not.4 The Python example with -O shows the result of an assertion used as the only check: the withdrawal goes through and the balance becomes negative. Check input with an ordinary test and an exception or an error value (Error value).
An assertion that cannot fail
In Python, assert (condition, "message") tests a tuple of two items. A tuple that is not empty is true, so the assertion never fails (see the tuple block of the Python example). In JavaScript, console.assert only writes a message and "does not otherwise affect execution", so a program that relies on it goes on with bad data.20
A test of the assertion state
Code that behaves differently when assertions are enabled can pass its tests and fail in production. The tests run with assertions on, and production runs with them off. Run at least some tests with the same settings as the release build.
Cost
- Run time. Each assertion that runs is a comparison and a branch, plus the cost of the expression. An invariant that walks a data structure can turn a constant-time operation into a linear-time one. This is the reason for
debug_assert!and for removal in release builds.114 - Removed assertions. A removed assertion costs nothing at run time. It also catches nothing.
- Static assertions. A static assertion costs nothing at run time. The compiler evaluates it once.6
- Code size. In C, each failed
assertwrites the text of the expression, the file name, the line and the function name, so these strings are in the program.6
History
- 1967 and 1969. Robert Floyd published "Assigning Meanings to Programs" in 1967, and C. A. R. Hoare published "An Axiomatic Basis for Computer Programming" in 1969. Meyer names the work of Floyd, Hoare and Dijkstra on program proving as one of the two primary sources of Design by Contract. He says that the class invariant comes directly from Hoare's data invariants.1
- 1992. Meyer's article "Applying Design by Contract" in IEEE Computer described preconditions, postconditions, class invariants, assertion monitoring, contracts under inheritance and the
rescueclause of Eiffel. It says that the use of assertions in an object-oriented language, and the approach to inheritance based on subcontracting, appear original to Eiffel.1 - 2002. JSR 41 added the
assertstatement to Java. Its final release was on 9 May 2002.14 - 2019. TypeScript 3.7, announced on 5 November 2019, added assertion functions with the return type
asserts condition.21
References
- Bertrand Meyer, Applying "Design by Contract", IEEE Computer 25(10), October 1992, pages 40 to 51, doi:10.1109/2.161279, page 42 (Figures 1 and 2, the three kinds of assertion); page 43 (the box Further sources); page 44 (assertion violations as bugs, Who should check?); page 45 (Class invariants, Figure 5); page 46 (Monitoring assertions, Why monitor?); page 48 (redeclaration under inheritance); pages 49 and 50 (failure, exceptions, the rescue clause)
- The Python Language Reference, Simple statements, Python 3.14, 7.3 The assert statement
- Python documentation, Command line and environment, Python 3.14, the option -O
- The Java Language Specification, Java SE 25 Edition, 14.10 The assert Statement, including the discussion at the end of the section
- The java Command, JDK 25, -enableassertions (-ea) and -disableassertions (-da)
- ISO/IEC 9899 working draft N3220 (C23), 6.7.12 Static assertions; 7.2.1 General (NDEBUG); 7.2.2.1 The assert macro
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [assertions.assert]
- .NET API reference, Debug.Assert Method, Remarks ("By default, the Debug.Assert method works only in debug builds") and the attribute ConditionalAttribute
- .NET API reference, ConditionalAttribute Class, the summary and the Remarks
- Rust standard library, macro assert, the description ("Assertions are always checked in both debug and release builds")
- Rust standard library, macro debug_assert, Uses
- Node.js documentation, Assert, assert.ok(value[, message])
- Jim Gray, Why Do Computers Stop and What Can Be Done About It?, Tandem Technical Report 85.7, June 1985, page 11, Fault containment through fail-fast software modules
- JSR 41, A Simple Assertion Facility, Java Community Process, Description and the stage timeline (Final Release, 09 May 2002)
- Kotlin documentation, Exceptions, Throw exceptions with precondition functions (require, check, error)
- Go FAQ, Why does Go not have assertions?
- TypeScript documentation, TypeScript 3.7 release notes, Assertion Functions
- PostgreSQL documentation, Constraints, 5.5.1 Check Constraints
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [structure.specifications], paragraph 3.3 (Preconditions)
- Node.js documentation, Console, console.assert(value[, ...message])
- Daniel Rosenwasser, Announcing TypeScript 3.7, TypeScript blog, 5 November 2019, Assertion Functions
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 2AHPC8 Edit this page History Report an error Markdown