Modelling with Types
Refinements, records, sums, and Option/Result as a substitute for defensive checks.
Contents
Types are the cheapest form of correctness. A property encoded in a type is checked at every construction and every assignment, and it does not have to be restated in each function. Idiomatic Haze moves every stable property it can into the type system, leaving contracts for the relationships that types cannot express.
The Modelling Ladder#
A value usually starts as a primitive and becomes more precise as the domain becomes clearer. The ladder below is a useful way to choose the representation.
| 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 at a lower level when the property depends on the call context or on a relationship between input and output.
Refinements for Scalar Domains#
A refinement gives a name and an invariant to a scalar. It is the smallest useful domain type, and it is especially valuable for identifiers, counts, and measures that are easy to mix up.
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 to a function that expects a user id is a compile error, even though both are positive integers. This is the main benefit of a nominal refinement over a comment or a naming convention.
A refinement is also the right place for a domain rule that is expensive to repeat in every precondition.
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 can be checked at construction. If the rule needs several fields, use a record invariant. If the rule is a relationship between an input and an output, use a postcondition.
Records for Grouped Data#
A record names a product and gives each field a precise type. It is the default representation for a domain object.
type Account {
id UserId
balance i64
}
type Transaction {
account UserId
amount i64
memo NonEmpty
}
The record makes the field names part of the type and prevents positional confusion. A function that takes Account cannot accidentally receive a Transaction with the same fields, because the two types are nominal.
A record with an invariant makes the relationship between fields explicit.
type Range : invariant lo <= hi {
lo i32
hi i32
}
type Window : invariant length <= 100 {
start i32
length i32
}
The first invariant prevents an inverted range. The second prevents a span that is too long. Both are checked at construction, so a function that receives a Window does not need to validate it again.
Sums for Alternatives#
A boolean flag is often a sign that the value has several states that should be separate variants. A sum type makes the states and their data explicit, and a match forces the code to handle each one.
type AccountState =
| Open(balance i64)
| Frozen(balance i64, reason NonEmpty)
| Closed(history List[Transaction])
The sum is better than a record with is_open, is_frozen, and closed_at fields because the invalid combinations cannot be constructed. A frozen account has a reason; an open account has a balance; a closed account has a history. A function that operates on an account matches the state and receives exactly the data that state provides.
fn available(state AccountState) i64 => match state {
Open(balance) => balance
Frozen(_, _) => 0
Closed(_) => 0
}
A sum is also the right shape for a protocol message, a parser result, a workflow step, or any value whose alternatives carry different data. It is not the right shape for a simple label with no payload; use an enum for that.
Enums for Closed Labels#
An enum names a closed set of labels. Use it when the value is a mode, a direction, a category, or a status that has no additional data.
type Direction enum {
North
East
South
West
}
type LogLevel enum {
Debug
Info
Warning
Err
}
The enum prevents a misspelled string and makes the set of possibilities visible in the type. When a label needs associated data, promote it to a sum type instead of adding a parallel record of optional fields.
Option and Result as Types#
Option and Result are not just control-flow helpers; they are type-level statements about partiality. A field or parameter that is an Option[T] says that absence is allowed. A return type that is a Result[T, E] says that 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
}
A Config with proxy: Option[str] cannot forget to distinguish "no proxy" from "empty proxy string". A load function with Result[Config, ConfigError] cannot silently return a default config when the file is missing.
Do not use Option for a field that is required. Do not use Result for a failure that the function cannot meaningfully report. A type that says too little is as misleading as one that says too much.
Newtypes Without Aliases#
Haze has no transparent type aliases. This is a feature for domain modelling: a named refinement is a distinct type, not a synonym. There is no way to accidentally treat a UserId as an OrderId after a rename.
type UserId = i32 : invariant self > 0
type OrderId = i32 : invariant self > 0
A function that has an i32 must construct the appropriate identifier before calling a function that expects a UserId or an OrderId. The construction is the validation point, and the rest of the program carries the refined type.
Parse at the Boundary#
The most effective use of types is to parse untrusted input once and then work with precise values. A parser returns a domain type or a structured error. The rest of the program does not repeat the checks.
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 has a Quantity and does not need to check for an empty string, a non-digit, or a non-positive value again. The error type preserves enough context to report the problem.
Replace Sentinels#
A sentinel value is a magic value that stands for a special case. It is easy to forget, easy to compare incorrectly, and invisible to the type checker. Replace it with a sum, an enum, or an Option.
| 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 |
A sentinel is sometimes appropriate in a low-level ABI or a packed format. In ordinary Haze code, it is almost always a missed opportunity to make the type say what the value means.
Model Transitions, Not Flags#
A state machine is clearer as a sum type and a transition function than as a record of booleans. The transition function takes a state and an event and returns the next state or an error.
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")
}
The match is exhaustive over the state and over the event in each state. The error type could be a sum instead of str when the caller needs to distinguish the reasons. The transition function is a natural place for a postcondition that relates the next state to the old one.
Avoid Stringly Typed APIs#
A string is a convenient carrier for anything, which is exactly why it is a poor type for a domain concept. A str parameter named mode accepts every string, including misspellings and values the function does not handle. An enum or a 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 still right for genuinely textual data: a message, a path, a name. The problem is using a string as a tag or a mode when the set of valid values is known.
Composition Over Inheritance#
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
}
The Customer contains an Address rather than extending an address type. The fields are explicit, the types are nominal, and the address can be reused by any other record that has an address. When two types share behaviour, express it as a trait; when they share data, express it as a field.
A Modelling 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 |
The next chapter, Functional Imperative Style, explains how to write the functions that consume these types.