Contents

Writing contracts first is a design discipline, not a formatting rule. The contract forces you to decide who is responsible for each condition before the implementation has a chance to blur the boundary. A function written contract-first is usually smaller, because the contract has already removed the cases the body would otherwise have to handle defensively.

Start with the Domain#

The first question is not "what does the function do?" but "what inputs is it willing to accept?" That answer becomes the precondition. A function that divides by a number must state that the number is nonzero. A function that indexes a list must state that the index is in range or return a Result. A function that accepts a percentage must state that the value is between zero and one hundred.

fn index_of(values List[i32], target i32) Option[i32] {
    for i in 0..values.len {
        if values[i] == target {
            return Some(i)
        }
    }
    return None
}

index_of has no precondition because every list and every target is in its domain. The absence of a result is represented by Option, not by a sentinel. This is a total function with a partial result, which is different from a function that requires a non-empty list.

fn first(values List[i32]) i32
    : pre values.len > 0
=> values[0]

first has a precondition because there is no sensible integer to return for an empty list. The caller must establish non-emptiness, or use head from the sequence library, which returns Option[i32] instead. The choice between the two is a design decision: a total function with an optional result, or a partial function with a caller obligation.

State the Guarantee#

The second question is "what may the caller rely on?" That answer becomes the postcondition. A postcondition should say something the return type alone does not. A function returning List[i32] does not promise that the list is sorted, that its length is preserved, or that its elements are positive. A postcondition can say all three.

fn sort(values List[i32]) List[i32]
    : post r => sorted(r)
    : post r => r.len == values.len
{
    // implementation
    return values
}

A postcondition that restates the return type, such as post r => r >= 0 for a function returning Positive, adds little because the type already guarantees it. A postcondition that relates the result to the input, or to a property that the type does not capture, earns its place.

fn deposit(account Account, amount i64) Account
    : pre amount > 0
    : post r => r.id == account.id
    : post r => r.balance == account.balance + amount
=> Account { id = account.id, balance = account.balance + amount }

The two postconditions say that the identity is preserved and that the balance changed by exactly the amount. Together with the precondition, they define the operation. The body is almost an afterthought because the contract has done the design work.

Choose the Right Mechanism#

Not every property belongs in a function contract. A condition on a single value belongs in a type. A condition that relates several fields belongs in a record invariant. A condition that depends on the call context belongs in a precondition. A condition that relates input to output belongs in a postcondition.

Property Best mechanism Example
A value is positive Refinement type type Positive = i32 : invariant self > 0
A range is ordered Record invariant type Range : invariant lo <= hi
A list is non-empty for this call Precondition pre values.len > 0
The result preserves the length Postcondition post r => r.len == values.len
The result is sorted Postcondition post r => sorted(r)
A loop maintains a relationship Loop invariant invariant total == i * (i - 1) / 2
An error message is exactly this text Test assert reason == "..."

Moving a property to the left of this table is usually an improvement. A repeated pre n > 0 on every function that accepts a count becomes a Positive parameter. A repeated check that two fields are ordered becomes a record invariant. The function contracts then describe the operation rather than the representation.

Write the Smallest Sufficient Contract#

A precondition that is too strong excludes valid calls. A precondition that is too weak forces the body to handle cases the caller did not intend. The right contract is the smallest assumption that makes the body correct and the largest guarantee that callers actually need.

fn average(values List[i32]) i32
    : pre values.len > 0
    : post r => r >= values[0] || values.len == 1
=> values[0]

The example above is intentionally weak and not a real average. A useful contract for a real average would state the divisor and the relationship to the sum. The point is that a postcondition should be worth checking. A clause that is always true, or that no caller would rely on, is noise.

A contract that is always false is a compile error. A contract that is always true is removed or ignored. Neither helps the reader. Aim for the middle: a property that is true for the implementation and useful to the caller, but not so complex that the compiler cannot evaluate it and a reader cannot verify it.

Use Pure Predicates#

A contract should be a property, not a procedure. Wrap a complex condition in a pure function with a name that states the domain rule.

pure fn funded(account Account, amount i64) bool =>
    amount > 0 && amount <= account.balance

pure fn has_room(account Account, amount i64) bool =>
    amount > 0 && account.balance + amount <= MAX_BALANCE

type Transfer {
    src Account
    dst Account
}

fn transfer(source Account, target Account, amount i64) Transfer
    : pre source.id != target.id
    : pre funded(source, amount)
    : pre has_room(target, amount)
    : post r => r.src.id == source.id
    : post r => r.dst.id == target.id
=> Transfer { src = source, dst = target }

The predicates are named after the domain rule, not after the comparison. A reader can understand the contract without parsing the arithmetic. The compiler can fold the predicates when their arguments are constant, because they are pure. An impure helper would force the clause into a runtime check.

Do Not Repeat Type Invariants#

If a type already guarantees a property, do not restate it in every function signature. A function that accepts a Positive does not need pre value > 0; the type already says it. Repeating the invariant adds an opportunity for the clauses to drift apart and makes the signature noisier.

type Positive = i32 : invariant self > 0

fn scale(value Positive, factor i32) Result[Positive, str]
    : pre factor > 0
=> Success(Positive { value * factor }?)

The precondition is about the factor, which is not refined. The Positive parameter needs no precondition because the type already guarantees it. The construction of the result uses checked construction because arithmetic on a refinement produces the base i32, not a Positive.

Avoid Mutating Parameters#

Haze has no old expression. A postcondition sees the final value of each parameter, so a function that mutates a parameter cannot state a relationship between the pre-state and the result without storing the pre-state in a local name.

fn clear(counter Counter) Counter
    : post r => r.n == 0
=> Counter { n = 0 }

The function returns a new counter. The caller can see the transition and the postcondition is a statement about the result. A version that mutates counter.n would need a different contract and would surprise a caller who expected the argument to be unchanged.

Local mutation is still fine. A loop that builds a list into a local var does not complicate the function's contract because the local is not part of the interface.

Loop Invariants#

Every loop whose correctness is not obvious should carry an invariant. The invariant should relate the loop variable to the accumulator and should hold at the header, including the terminal check for a range loop.

fn running_total(values List[i32]) List[i32]
    : post r => r.len == values.len
{
    var out List[i32] = []
    var total = 0
    for i in 0..values.len
        : invariant out.len == i
    {
        total += values[i]
        out += [total]
    }
    return out
}

The invariant says that one output has been produced per input processed. A reader can see why the postcondition holds, even though the compiler checks the clause independently.

Contract Density#

Not every private helper needs a full contract. The right density depends on visibility and risk.

Function kind Suggested contract density
Public API Preconditions for every non-obvious domain restriction; postconditions for every guarantee callers rely on
Private helper with a narrow purpose A precondition when the caller obligation is not obvious; a postcondition when the result is non-trivial
Pure predicate No contract beyond its type; the body is the definition
Trait method Contracts on the implementation; contracts on the declaration for documentation and defaults
Test helper No contracts; assertions or Result are clearer

A public function with no contract is making an implicit claim that every value in its parameter types is acceptable. That claim is often false. A private helper called in one place can rely on the caller's context and may not need to repeat it.

A Refactoring Sequence#

The following sequence turns a defensive function into a contract-first function.

// Before: the body checks everything and the caller cannot tell what is guaranteed.
fn withdraw_before(account Account, amount i64) Result[Account, str] {
    if amount <= 0 {
        return Error("amount must be positive")
    }
    if amount > account.balance {
        return Error("insufficient funds")
    }
    return Success(Account { id = account.id, balance = account.balance - amount })
}

The Result is doing two jobs. It models an expected failure and it validates a programming error. A better design separates the cases.

contract Funded(account Account, amount i64) {
    pre amount > 0
    pre amount <= account.balance
}

fn withdraw(account Account, amount i64) Account
    : Funded(account, amount)
    : post r => r.id == account.id
    : post r => r.balance == account.balance - amount
=> Account { id = account.id, balance = account.balance - amount }

The operation is now total within its domain. A caller that cannot prove the domain must establish it before the call, or use a fallible variant that returns Result for the expected reasons. The contract-first version is shorter, clearer, and easier to compose.

Summary#

Decision Question Mechanism
Domain What inputs are acceptable? Precondition or a narrower parameter type
Guarantee What may the caller rely on? Postcondition
Valid value What makes a value of this type valid? Refinement or record invariant
Loop correctness What remains true at the header? Loop invariant
Expected failure Can this operation fail legitimately? Result
Absence Can the value be missing? Option
Concrete example Is this one behavior correct? Test with assert

The next chapter, Modelling with Types, explains how to move properties out of contracts and into the type system so that the contracts can become smaller.