Contents

A property encoded in a type is checked at every construction and assignment. Move every stable property into the type system, leaving contracts for relationships types cannot express.

Modelling Ladder#

Level Representation Guarantees Example
1 Primitive None beyond the primitive's range i32
2 Refinement A predicate on the value Positive
3 Record A named product with typed fields Account
4 Invariant record Relations between fields Range with lo <= hi
5 Sum Exactly one of several alternatives AccountState
6 Generic container A shape parameterized by element type List[Transaction]

Move down the ladder when a property is stable, checkable at construction, and useful to more than one function. Stay lower when the property depends on the call context or on a relationship between input and output.

Refinements#

type UserId = i32 : invariant self > 0
type OrderId = i32 : invariant self > 0
type Quantity = i32 : invariant self > 0
type Percentage = i32 : invariant self >= 0 && self <= 100

UserId and OrderId have the same representation but are different types. Passing an order id where a user id is expected is a compile error.

type NonEmpty = str : invariant self.len > 0
type Even = i32 : invariant self % 2 == 0
type Port = i32 : invariant self > 0 && self <= 65535

Use a refinement when the rule is simple and checkable at construction, a record invariant when the rule relates several fields, and a postcondition when the rule relates input and output.

Records#

type Account {
    id      UserId
    balance i64
}

type Transaction {
    account UserId
    amount  i64
    memo    NonEmpty
}

A function that takes Account cannot receive a Transaction with the same fields.

type Range : invariant lo <= hi {
    lo i32
    hi i32
}

type Window : invariant length <= 100 {
    start  i32
    length i32
}

Both invariants are checked at construction.

Sums#

A boolean flag often means the value has several states that should be separate variants.

type AccountState =
    | Open(balance i64)
    | Frozen(balance i64, reason NonEmpty)
    | Closed(history List[Transaction])
fn available(state AccountState) i64 => match state {
    Open(balance) => balance
    Frozen(_, _) => 0
    Closed(_) => 0
}

Use a sum when alternatives carry different data. Use an enum for a label with no payload.

Enums#

type Direction enum {
    North
    East
    South
    West
}

type LogLevel enum {
    Debug
    Info
    Warning
    Err
}

When a label needs associated data, promote it to a sum type.

Option and Result#

A field or parameter of type Option[T] says absence is allowed. A return type of Result[T, E] says the operation may fail and names the error domain.

type Config {
    name      NonEmpty
    proxy     Option[str]
    retry_max i32
}

fn load(path str) Result[Config, ConfigError] {
    // parse the file into a Config
}

Do not use Option for a required field. Do not use Result for a failure the function cannot meaningfully report.

Newtypes#

Haze has no transparent type aliases. A named refinement is a distinct type.

type UserId = i32 : invariant self > 0
type OrderId = i32 : invariant self > 0

An i32 must be constructed as the appropriate identifier before use.

Parse at the Boundary#

type Quantity = i32 : invariant self > 0

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

fn check_quantity(value i32) Result[Quantity, str] =>
    Success(Quantity { value }?)

fn parse_quantity(text str) Result[Quantity, ParseError] {
    if text.len == 0 {
        return Error(Empty)
    }
    var value = 0
    for i in 0..text.len {
        const digit = text[i]
        if digit < 48 || digit > 57 {
            return Error(InvalidDigit(i, digit))
        }
        value = value * 10 + cast[i32](digit - 48)
    }
    return match check_quantity(value) {
        Success(quantity) => Success(quantity)
        Error(_) => Error(OutOfRange)
    }
}

After parse_quantity, the caller does not re-check emptiness, digits, or positivity.

Replace Sentinels#

Sentinel pattern Better representation
-1 means not found Option[i32]
"" means missing Option[NonEmpty]
0 means unlimited A sum with Unlimited and Limited(count)
null pointer Option[T] or a sum
Error code plus out-parameter Result[T, E]
Several boolean flags A sum type with one variant per state

Sentinels may be appropriate in a low-level ABI or packed format.

Model Transitions#

type UserId = i32 : invariant self > 0
type NonEmpty = str : invariant self.len > 0

type State =
    | Draft
    | Reviewing(reviewer UserId)
    | Published(at i64)
    | Rejected(reason NonEmpty)

type Event =
    | Submit
    | Approve(reviewer UserId)
    | Reject(reason NonEmpty)

fn transition(state State, event Event) Result[State, str] => match state {
    Draft => match event {
        Submit => Success(Reviewing(UserId { 1 }))
        _ => Error("draft only accepts submit")
    }
    Reviewing(reviewer) => match event {
        Approve(next) => Success(Published(0))
        Reject(reason) => Success(Rejected(reason))
        Submit => Error("already submitted")
    }
    Published(_) => Error("published is final")
    Rejected(_) => Error("rejected is final")
}

Avoid Stringly Typed APIs#

A str parameter named mode accepts every string. An enum or sum makes the accepted set visible.

type LogLevel enum {
    Debug
    Info
    Warning
    Err
}

fn should_log(level LogLevel, configured LogLevel) bool =>
    rank(level) >= rank(configured)

fn rank(level LogLevel) i32 => match level {
    LogLevel.Debug => 0
    LogLevel.Info => 1
    LogLevel.Warning => 2
    LogLevel.Err => 3
}

A string is right for genuinely textual data: a message, a path, a name.

Composition#

Haze has no record inheritance. Reuse comes from composition, generics, and traits.

type Address {
    street NonEmpty
    city   NonEmpty
}

type Customer {
    id      UserId
    name    NonEmpty
    address Address
}

Express shared behaviour as a trait and shared data as a field.

Checklist#

Question If yes If no
Is the value always one of a fixed set of alternatives? Use a sum or enum Use a record or scalar
Does the value have a scalar domain rule? Use a refinement Use the scalar
Do several fields constrain one another? Use a record invariant Use plain fields
Can the value be absent? Use Option Use the value
Can the operation fail for expected reasons? Use Result Return the value
Is the value an identifier for a distinct concept? Use a nominal refinement Do not invent a wrapper
Are two values easy to confuse? Give them distinct types Use names and comments
Is the rule only true for this call? Use a precondition Move it to a type