01 / 21

Function Contracts
& Invariants

Learn to define precise contracts for your functions: what goes in, what comes out, and what must always remain true.

JavaScript

What Is a Function Contract?

A function contract is a precise description of the agreement between a function and its callers. It specifies three things: what the function expects as input, what it promises to return, and any conditions that must hold before and after execution.

The Three Parts of a Contract

Preconditions
What must be true before the function runs. Rules about the inputs the caller must satisfy.
Postconditions
What the function guarantees after it returns. The promise about the output value.
Invariants
What must be always true: before, during, and after the function executes.

How a Contract Works

Caller provides input Precondition validate inputs Function executes logic Postcondition verify output Output guaranteed result Invariant always holds true before, during, after e.g. array stays sorted

The Formal Contract Pattern

/** * Contract for: functionName * * @param {Type} paramName - description * @returns {Type} - description * * @precondition paramName must satisfy [rule] * @postcondition return value satisfies [guarantee] * @invariant [property] is preserved */ function functionName(paramName) { // implementation }

Preconditions: Guard the Entrance

A precondition is a boolean condition that must be true when the function is called. If the caller violates a precondition, the function's behavior is undefined: it may crash, return garbage, or silently corrupt data.

/** * @precondition n must be a non-negative integer * @precondition \(n \le 170\) (avoids Infinity) */ function factorial(n) { if (n === 0) return 1; return n * factorial(n - 1); }

Postconditions: Guarantee the Exit

A postcondition is a promise the function makes about its return value and any side effects. If the function's implementation is correct and preconditions were met, the postcondition must hold.

/** * @param {number[]} arr - array of numbers * @returns {number} the largest element * * @precondition \(arr.length > 0\) * @postcondition \(result \ge\) every element in arr * @postcondition result is an element of arr */ function findMax(arr) { return Math.max(...arr); }

Invariants: Always True

An invariant is a property that must be maintained throughout execution. Unlike pre/postconditions (which apply at specific moments), invariants hold before, during, and after every operation.

/** * A sorted array wrapper. * * @invariant this.items is always sorted ascending */ class SortedList { constructor() { this.items = []; } // @precondition val is a number // @postcondition val is in this.items insert(val) { let i = this.items.findIndex(x => x > val); if (i === -1) i = this.items.length; this.items.splice(i, 0, val); } }

Contracts vs. Type Checking

Contract Type Check
Scope Logical rules about values Structural rules about types
Example \(n > 0\) n: number
Catches Semantic errors Syntax / shape errors
When checked Runtime (or by developer) Compile time (TypeScript) or runtime
Can express "array is sorted", "\(\text{result} < \text{input}\)" "param is a string[]"

Writing Contracts: Step by Step

1
Name each parameter and state its type. What kind of value does the function receive?
2
State preconditions. What must be true about each input? Think: range, length, non-null, format.
3
Describe the return value. What type? What does it represent?
4
State postconditions. What is guaranteed about the result? Relate it back to the inputs.
5
Identify invariants. Does the function modify shared state? If so, what property must the state always satisfy?

Example 1: Average of an Array

/** * Computes the arithmetic mean of an array. * * @param {number[]} nums - array of numbers * @returns {number} the arithmetic mean * * @precondition \(nums.length > 0\) * @precondition every element is a finite number * @postcondition \(result \ge \min(nums)\) * @postcondition \(result \le \max(nums)\) * @invariant nums is not modified */ function average(nums) { const sum = nums.reduce((a, b) => a + b, 0); return sum / nums.length; }
Precondition
Non-empty array of finite numbers: no NaN, no Infinity
Postcondition
Result falls between the smallest and largest elements
Invariant
Original array is never mutated: pure computation

Example 2: Binary Search

/** * Finds the index of target in a sorted array. * * @param {number[]} arr - sorted ascending * @param {number} target - value to find * @returns {number} index of target, or -1 * * @precondition arr is sorted in ascending order * @postcondition if \(result \neq -1\), then \(arr[result] === target\) * @postcondition if result === -1, target is not in arr * @invariant arr is not modified */ function binarySearch(arr, target) { let lo = 0, hi = arr.length - 1; while (lo <= hi) { const mid = (lo + hi) >>> 1; if (arr[mid] === target) return mid; if (arr[mid] < target) lo = mid + 1; else hi = mid - 1; } return -1; }

Example 3: Loop Invariants

A loop invariant is a special type of invariant that holds true at the start and end of every iteration of a loop. It is a powerful tool for reasoning about correctness.

/** * @precondition arr is an array of numbers * @postcondition result === sum of all elements */ function sumArray(arr) { let total = 0; // Loop invariant: total === sum of arr[0..i-1] for (let i = 0; i < arr.length; i++) { total += arr[i]; // invariant: total === sum of arr[0..i] } return total; }

Enforcing Contracts at Runtime

Contracts can be documented (comments only) or enforced (with runtime checks). Enforcement turns silent bugs into loud, immediate errors:

function divide(a, b) { // Enforce precondition if (typeof a !== 'number' || typeof b !== 'number') { throw new TypeError('Both args must be numbers'); } if (b === 0) { throw new RangeError('Divisor must not be zero'); } const result = a / b; // Enforce postcondition (debug check) console.assert(Number.isFinite(result), 'Result is finite'); return result; }

Common Mistakes

✕ Missing Preconditions
Assuming callers will always provide valid input. If a function needs a non-empty array, state it.
✕ Vague Postconditions
Writing "returns the answer" instead of a precise, verifiable statement like \(\(result \ge 0\) and \(\text{result} < \text{arr.length}\)\).
✕ Broken Invariants
Adding a method that mutates state without maintaining the class invariant: e.g., pushing unsorted values into a SortedList.

Summary at a Glance

Concept When Who's responsible Example
Precondition Before call Caller \(arr.length > 0\)
Postcondition After return Function result is sorted
Invariant Always Both list stays sorted
Type contract At boundary Tooling param: number[]

Question 1 of 5

A function sqrt(n) has the contract: "n must be non-negative." What kind of contract clause is this?

Question 2 of 5

For the function findMax(arr), which of these is a valid postcondition?

Question 3 of 5

A SortedList class has an invariant: "items is always sorted ascending." Which operation would violate this invariant?

Question 4 of 5

Which contract clause best describes: "the returned value is always between min and max, inclusive"?

Question 5 of 5

What is the key difference between a contract and a type annotation like n: number?