Contents

Idiomatic Haze decides where each guarantee belongs. Types, contracts, tests, and Result answer different questions.

Bugs and Expected Failures#

A bug is a caller passing an input outside the function's domain, or an implementation returning a value outside its guarantee. Bugs are handled by contracts and type invariants. A runtime contract violation panics.

An expected failure is an operation that may legitimately fail: a missing file, invalid input, a refused request. Expected failures are values, modelled with Result[T, E], handled with match or is, and propagated with ?.

Situation Mechanism Failure behaviour
Input violates a documented domain Precondition Abort, because the caller has a bug
Implementation breaks a guarantee Postcondition Abort, because the implementation has a bug
A value would violate a type invariant Refinement plus checked construction Error returned by ?
An operation may fail for environmental reasons Result[T, E] Returned to the caller
A value may be absent Option[T] Returned to the caller
A concrete example needs checking Test with assert Test failure

Do not return Result for a programming error. Do not panic on a missing file. Do not use a sentinel such as -1 when Option is available. Do not restate a type invariant in every precondition.

Hierarchy of Guarantees#

When more than one mechanism can express a property, choose the one closest to the value.

Rank Mechanism Best for Example
1 Type The shape of the value and its valid states A sum type with one variant per state
2 Refinement or record invariant A predicate checkable at construction Positive, a range with lo <= hi
3 Precondition A caller obligation that depends on the call context A non-empty list, a divisor, an index
4 Postcondition A relationship between inputs and outputs A sorted result, a preserved length
5 Loop invariant A property maintained by each iteration An accumulator's relationship to the index
6 Test A concrete behaviour that is not a general law An error message, deferred cleanup order
7 Comment Context that is not a checkable claim Why an algorithm was chosen

The hierarchy is a preference, not a prohibition. A test is the right tool for verifying an error message. A comment is the right tool for explaining a trade-off. The mistake is using a comment for a property that a type or contract could enforce.

Contracts Before Bodies#

Write the contract before the body. State the domain, state the result guarantee, choose types that make the guarantee natural, then write the control flow.

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 body is a single expression because the design has made the operation total within its domain. A conditional handling a case the contract did not mention would mean the contract is incomplete.

Types Before Contracts#

A property that can be represented in a type should not be repeated in function signatures. A positive integer is a Positive, not an i32 with pre n > 0 on every function. An absent value is an Option, not a sentinel. Mutually exclusive states are a sum type, not a record with flags that can contradict one another.

type Positive = i32 : invariant self > 0

type AccountState =
    | Open(balance Positive)
    | Frozen(balance Positive, reason str)
    | Closed(history List[Transfer])

Functional Composition#

Loops are clear for stateful processes, early return for validation, and a local var for an accumulator. A transformation over a collection is usually clearer as a pipeline of small pure functions.

fn active_names(accounts List[Account]) List[str] =>
    accounts
        .filter(is_open)
        .map(fn(account) => account.name)

Use a loop when the transformation needs an index, a running total, or an early exit.

Immutable Data Flow#

Prefer producing a new value to mutating a shared one. A postcondition describes the relationship between arguments and the result. If the function also mutates an argument, the postcondition sees the mutated value because there is no old expression.

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

Local mutation is fine. Do not mutate a parameter or shared value unless mutation is the documented purpose of the function.

Errors at the Boundary#

Parse and validate at the boundary, then work with precise types inside.

type ParseError =
    | Empty
    | InvalidDigit(position i32, character u8)

fn parse_positive(text str) Result[Positive, ParseError] {
    if text.len == 0 {
        return Error(Empty)
    }
    const result = parse_i32(text)?
    return Success(Positive { result }?)
}

FFI#

C FFI is discouraged. Contracts, purity, managed values, and the error model do not cross the C boundary. An extern function has no contracts, cannot be pure, and deals in cstr, ptr, and C-layout records.

Use FFI only for a capability the language and standard library do not provide. Keep the extern surface small, convert to Haze types immediately, and expose a checked Haze function with contracts and Result errors. See The FFI Boundary.

Review Questions#

Question Why it matters
Does every public function state its domain and guarantee? The contract is the interface
Could a type or refinement carry a property that is currently a repeated check? Types remove whole classes of error
Are expected failures Result or Option rather than panics or sentinels? The caller can handle them
Does the function mutate a parameter or a shared value? Mutation complicates contracts and aliasing
Is the collection operation expressed at the right level? A pipeline describes a transformation; a loop describes a process
Is every non-obvious loop accompanied by an invariant? The invariant is the loop's contract
Is cleanup expressed with defer? Scope-based cleanup is reliable on every exit path
Is FFI isolated behind a checked wrapper? The boundary is where guarantees are lost
Are the boundary cases tested? Contracts state laws; tests exercise examples