Function Contracts
& Invariants
Learn to define precise contracts for your functions: what goes in, what comes out, and what must always remain true.
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
How a Contract Works
The Formal Contract Pattern
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.
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.
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.
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
Example 1: Average of an Array
Example 2: Binary Search
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.
Enforcing Contracts at Runtime
Contracts can be documented (comments only) or enforced (with runtime checks). Enforcement turns silent bugs into loud, immediate errors:
Common Mistakes
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
Consider this function:
function clamp(val, min, max) {
if (val < min) return min;
if (val > max) return max;
return val;
}
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?