Contents

Writing contracts first forces a decision about who is responsible for each condition before the implementation blurs the boundary.

Start with the Domain#

The first question is what inputs the function accepts. That answer becomes the precondition.

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 target is in its domain. Absence is represented by Option, not a sentinel.

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

first has a precondition because there is no integer to return for an empty list. A caller must establish non-emptiness or use an Option-returning variant. A total function with an optional result and a partial function with a caller obligation are both valid designs.

State the Guarantee#

The second question is what the caller may rely on. That answer becomes the postcondition. A postcondition should say something the return type alone does not.

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 adds little. A postcondition that relates the result to the input 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 }

Choose the Right Mechanism#

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 == "..."

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.

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 callers need.

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

A clause that is always true, or that no caller would rely on, is noise. A clause that is always false is a compile error.

Pure Predicates#

Wrap a complex condition in a pure function named after 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 }

A pure predicate can be folded when its arguments are constant. An impure helper forces a runtime check.

Do Not Repeat Type Invariants#

A function that accepts a Positive does not need pre value > 0.

type Positive = i32 : invariant self > 0

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

Arithmetic on a refinement produces the base i32, so the result uses checked construction.

Avoid Mutating Parameters#

There is no old expression. A postcondition sees the final value of each parameter.

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

Local mutation does not complicate the contract because the local is not part of the interface.

Loop Invariants#

A loop whose correctness is not obvious should carry an invariant relating the loop variable to the accumulator.

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
}

Contract Density#

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 claims that every value in its parameter types is acceptable.

Refactoring Sequence#

A defensive version checks everything in the body:

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 models both an expected failure and a programming error. Separate them:

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 total within its domain. A caller that cannot prove the domain must establish it or use a fallible variant.

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 behaviour correct? Test with assert