What Belongs in the Type System
Several sources study these ideas systematically, although there is no universally accepted “type-system design methodology.” This note collects the parts that do exist: what each kind of check is good for, which properties make good types, a decision procedure, and what the approach costs.
Types, contracts, runtime checks and tests
Types, runtime checks, and tests handle program assumptions in complementary ways:
Program assumptions
│
┌─────────────────┼──────────────────┐
▼ ▼ ▼
Types Runtime Tests
│ checks │
│ │ │
prove broadly check current sample actual
and statically reality executionsThey’re complementary.
Each covers a gap the others leave:
- Types say something about every run, but only properties the type language can express, and only about code the checker sees.
- Runtime checks handle what the code can’t know in advance: input from outside. They’re exact, but only about the value in front of them, at that moment.
- Tests run real code on chosen inputs. They can check anything you can compute (that a list is sorted, that totals add up), but only for the cases someone thought of.
An analogy from building: the plan review (types) rules out whole classes of mistakes before anything is built; the inspector at the loading dock (runtime checks) examines each delivery as it arrives; the fire drill (tests) shows that particular scenarios work. Parse Dont Validate is how the second feeds the first: check once at the boundary, then let the type carry the result.
Bragilevsky (PDF, section 13.2.1 “Safety in Haskell programs”) gives the working Haskell version of the same split: check at compile time everything that can be checked there, write tests for the other properties of the program, and handle what arrives at run time with checks and error reporting. He adds that types are weak at describing run-time input: if a user supplies a list, nothing at compile time knows how long it is.
Contracts are the fourth tool, and they sit between types and runtime checks. In Design by Contract, as The Pragmatic Programmer (PDF, Topic 23 “Design by Contract”) describes it, a routine states preconditions (what the caller must guarantee), postconditions (what the routine guarantees in return) and invariants. Two of its points carry over directly to types:
- A broken contract is a bug, not a normal outcome. That’s why, Thomas and Hunt say, preconditions shouldn’t be used to validate user input. Input that may be wrong isn’t a precondition; it’s something to parse.
- The caller is responsible for meeting the precondition. A refined parameter type (
sqrt(x: NonNegative)) is a precondition the compiler enforces at every call site, and the check moves to wherever the caller first got the value.
They also argue that contracts are less repetitive than defensive programming, where every routine re-checks its inputs because it can’t trust its callers. A type that carries the checked property is the same idea taken one step further: the check happens once and the type remembers it.
Contracts can also be the run-time half of a type system. In Typed Racket, the standard example of macro gradual typing (see Dimensions Of Type Systems), a type on an import from untyped code turns into a contract checked whenever a value crosses the boundary.
A good type-system target
There is a fairly clean way to reason about when something belongs in the type system.
That gives a useful principle:
Put a property in the type system when it is stable, mechanically checkable, and useful to know throughout the program.
“Stable” has a sharper version in The Pragmatic Programmer’s idea of semantic invariants (Topic 23): requirements central to the meaning of a thing, as opposed to policies that a new management could change. Their example is a debit-card switch that must never apply the same transaction twice. A semantic invariant is a good candidate for a type. A policy (a free-shipping threshold, a discount rule) is better as data or as a function, because it will change, and a type change ripples through every signature that mentions it.
The last row of the table fails for a different reason: ordinary types check safety properties (“nothing bad happens”, violated at an identifiable step), whereas “service eventually answers” (“guaranteed service”) is a liveness property (“something good eventually happens”, which no finite prefix of a run can falsify; Alpern and Schneider, PDF, sections 2 and 3).
A decision procedure
Proposed decision procedure:
- Ask what invariant you’re currently checking mentally, in comments, or repeatedly with
if. - Ask whether violating it represents a programming error.
- Ask whether the invariant remains true once established.
- Ask whether many downstream functions benefit from knowing it.
- See whether your language can represent it simply.
- If the type representation becomes much harder to understand than the invariant itself, use runtime validation/tests.
Question 2 is the Design by Contract distinction above: a violation that’s a bug belongs in a precondition or a type, while a violation that’s a normal business outcome (the balance is too low) belongs in the result type. Parsons (PDF, chapters 10 and 11) calls those two moves pushing responsibility back (restricting the domain, as with NonEmpty, which ripples checks back to the edges of the system) and pushing it forward (expanding the range with Maybe or Either); Ousterhout (PDF, chapter 10, “Define Errors Out Of Existence”) adds a third option when callers don’t need the distinction: define the operation’s semantics so the edge case is normal behaviour (as Python’s out-of-range slice returns []). Question 6 is the one Maguire, an advocate of type-level programming, puts first (PDF, Introduction): when in doubt, don’t do it at the type level.
Applied to two invariants:
cart is non-empty at checkout balance covers a withdrawal
1. checked repeatedly? yes: pricing, shipping, UI yes
2. violation is a bug? yes: checkout shouldn't be no: it's a normal business
reachable with an empty cart outcome
3. stays true? yes, once the cart is frozen no: another transaction
for checkout can change it
4. many users downstream? yes few: the withdrawal itself
5. simple to represent? yes: NonEmptyList no: needs dependent types
→ put it in the type check at runtime, put the
failure in the result typeQuestion 3 decides the second case on its own. A fact that can stop being true is a poor type, however useful it would be downstream.
A particularly good signal is repeated defensive code:
if (user != null)
if (order.status === "paid")
if (items.length > 0)
if (currency === expectedCurrency)
if (resource.isOpen)When the same check appears throughout a codebase, there’s often missing information in the types.
In a gradually typed language the procedure also says where to start. Slatkin’s advice for Python (PDF, Item 90) is to annotate the public APIs and the most error-prone code first, not to aim for full coverage (returns diminish), and to skip annotations for prototypes and small scripts.
Where types stop matching reality
There is, however, a limit.
Suppose you want:
withdraw(account, amount)with the invariant:
amount <= current account balanceYou could imagine an extremely sophisticated dependent type:
withdraw :
Account<balance = b>
-> Amount<a where a <= b>
-> Account<balance = b-a>But your balance lives in a database and another transaction may modify it.
At that point, encoding the property entirely into compile-time types stops matching reality. The database transaction is the authority. Helland (PDF, section 2 “Data: Then and Now”) puts the boundary in temporal terms: ACID serializability gives a service’s inside data a crisp “now”, whereas any value read out of it unlocks and becomes a “blast from the past”, and an outgoing withdraw request is only “hope for the future” until the transaction runs.
That doesn’t leave types with nothing to say. They can’t prove that the balance is enough, but they can force every caller to deal with the case where it isn’t:
def withdraw(account: AccountId, amount: PositiveAmount): IO[Either[InsufficientFunds, Balance]]The amount being positive is a stable fact about the value, so it goes in the type. Whether the balance covers it is a fact about the world, checked inside the transaction. What reaches the type is the possibility of failure, as a value the caller can’t ignore. That’s the usual division of labour: types for what’s true of the value, runtime checks for what’s true of the world, and the result type for the outcome of the check.
“Facts about the value stay true” has a precondition of its own: the value must be immutable. Bloch (PDF, Item 50 “Make defensive copies when needed”) shows a Period class that checks start <= end in its constructor and is still broken, because the caller keeps a reference to the mutable Date objects and changes them afterwards. His fix is to copy the inputs before checking them, so another thread can’t change them between the check and the copy (a time-of-check/time-of-use attack). In a language with mutable objects, a validated type is only as good as its defensive copies.
Persistent data has the same problem over a longer time span: a value checked when it was written may be read years later by code with different rules. See Types At The Boundary.
The cost of stronger guarantees
So there’s a tradeoff:
stronger static guarantees
▲
│
dependent types │
refinement types │
session types │
linear types │
│
algebraic data types │
generics │
│
primitive types │
└──────────────────────►
proof/complexity costRefinement types sit below dependent types: Jhala et al. (PDF, chapter 1) describe them as a restricted class of dependent types whose logic is limited so that an SMT solver can do the proving automatically. That trade, less expressiveness for much less proof work, is why they’re the practical step between ordinary types and full dependent types; see Refinement Types.
Pierce (PDF, chapter 1) puts the whole ladder in a wider frame: type systems are lightweight formal methods, at the opposite end from Hoare logic and other heavyweight verification, and climbing the ladder moves you along that line. Bornholt et al. (PDF, sections 1, 6 and 8.2) show where a production team hands off along it on S3’s Rust storage node: Rust’s type system rules out memory bugs and data races, while executable reference models, property-based conformance tests and stateless model checking cover API equivalence, crash consistency and higher-level concurrency at about 20% test-and-model code overhead, against 3-10x for full proof.
Costs and failure modes
The approach has costs, and it can go wrong:
- Conversion code. Every new type needs a constructor, serialization, and mapping at each boundary. A domain with twenty value types has twenty of each.
- Types that lie. A type is only as trustworthy as the code that constructs it. A
PaidOrderproduced by a deserializer that never checks payment is worse than a plainOrder, because readers trust it. The usual culprits are hidden constructors: a JSON decoder or derivedReadinstance, a case class’scopymethod, Java deserialization (Bloch, Item 88, callsreadObject“effectively another public constructor”). See Strength Of Evidence. - Facts that expire. A balance, a session or a lock can stop being true after it’s checked, so it makes a poor type. See Where types stop matching reality above.
- Modeling too early. When the domain is still unclear, precise types make every change touch many places. The compiler makes those changes safe but not free. Starting looser and tightening as invariants settle is often the cheaper path. Wlaschin (PDF, chapter 5) offers a middle way: sketch the model with placeholder types (
type Undefined = exn) for the parts you don’t understand yet, so the shape compiles before the details exist. - Rejected correct programs. The checker is conservative (Type Systems), and each workaround (a cast,
Any,unsafeCoerce) is a small hole in the guarantee. - Error messages. Advanced encodings produce errors about type families or failed implications rather than about the domain. Maguire (chapter 12, “Custom Type Errors”) makes the point that a type-safe library is no use if nobody can work out how to use it, and spends a chapter on custom error messages for that reason.
- Inconvenient interfaces. Bragilevsky (section 13.2.1) notes that the safer an interface is, the less convenient it usually is to use:
headon aNonEmptylist is safe, but the caller has to produce theNonEmptyfirst. - Readability. Advanced encodings (type-level programming, heavy use of
F[_]) can be harder to understand than the invariant they protect, and their implementation details leak: Parsons (PDF, section 20.7 “Type Families”) shows a length-indexedVectorappendrejected becauseAdd ('Succ n) m = Add n ('Succ m)and'Succ (Add n m), though equal on numbers, don’t reduce the same way in the checker, and (chapter 12, “The Trouble with Typed Errors”) how fine-grained typed errors either collapse into an over-wideAllErrorsEversum or accumulate mapping boilerplate that can’t discharge a handled case. The rule of thumb below is the guard against this. - Compile time and team cost. Type-level machinery slows compilation, steepens the learning curve for the rest of the team, and adds friction whenever the model changes, since every invariant in the types has to be kept consistent. Parsons (“Principles”: “Complexity” and “Novelty”; chapter 9, “Optimizing GHC Compile Times”) treats advanced features as spending a finite complexity and novelty budget that multiplies across call sites, narrows hiring and onboarding, stiffens code when business rules change what counts as valid, and (through large shared
Typesmodules, generic deriving and unisolatedTemplateHaskellsplices) triggers recompilation cascades across the build.
Rule of thumb
A suggested rule for ordinary application design is: use types to capture stable facts that would otherwise have to be remembered by programmers. That’s where the compiler tends to give the highest return for the added type complexity.
Related: Type Systems for what a type system can prove, Parse Dont Validate for carrying a checked property through the program, Refinement Types for the stronger end of the cost curve, and Scala Type System for the Scala libraries that encode contracts in types.
Library sources
- Thomas et al. 2020, The Pragmatic Programmer, 2nd Edition – Topic 23, “Design by Contract”: preconditions as the caller’s responsibility, not for input validation, and semantic invariants versus policy; on Types, contracts, runtime checks and tests, A good type-system target and A decision procedure
- Bragilevsky 2021, Haskell in Depth – section 13.2.1, “Safety in Haskell programs”: types, tests and runtime checks, and safety against convenience; on Types, contracts, runtime checks and tests and Costs and failure modes
- Parsons 2023, Production Haskell – “Principles” (“Complexity” and “Novelty”) on complexity and novelty budgets and how safety features resist changing requirements; chapter 9, “Optimizing GHC Compile Times”, on
Project.Typesmegamodules, generic deriving andTemplateHaskellrecompilation cascades; chapters 10 and 11, “Type Safety Back and Forth” and “Keep Your Types Small…”, on pushing responsibility back (restricting the domain) versus forward (expanding the range); chapter 12, “The Trouble with Typed Errors”, on monolithic error sums versus non-decomposable constraints; section 20.7, “Type Families”, on type-level implementation details leaking into proofs; on A decision procedure and Costs and failure modes - Ousterhout 2018, A Philosophy of Software Design – chapter 10, “Define Errors Out Of Existence” (and sections 10.9-10.10): redefining an operation’s semantics so edge cases are normal behaviour rather than exceptions or special error returns, while keeping errors exposed when callers genuinely need them; on A decision procedure
- Helland 2005, Data on the Outside versus Data on the Inside – section 2, “Data: Then and Now” (and section 3 on immutable, versioned outside data): ACID serializability gives inside data a crisp “now”, while unlocked data sent outside is from the past and operator requests live in the future; on Where types stop matching reality and Costs and failure modes
- Bloch 2018, Effective Java, 3rd Edition – Item 50 on defensive copies and time-of-check/time-of-use, Item 88 on
readObjectas a hidden constructor; on Where types stop matching reality and Costs and failure modes - Alpern et al. 1985, Defining Liveness – sections 2 and 3: safety properties prohibit a discrete bad thing, whereas liveness properties (“guaranteed service”: every request is eventually satisfied) leave every finite prefix remediable; on A good type-system target
- Bornholt et al. 2021, Using Lightweight Formal Methods to Validate a Key-Value Storage Node in Amazon S3 – sections 1, 6 and 8.2: where Rust’s type and data-race guarantees stop on a 44k-line storage node, and how executable Rust reference models, property-based conformance tests and stateless model checking validate crash consistency and concurrency at 20% code overhead against 3-10x for full verification; on The cost of stronger guarantees
- Jhala et al. 2020, Programming with Refinement Types – chapter 1: refinement types as a restricted class of dependent types; on The cost of stronger guarantees
- Maguire 2018, Thinking with Types – the Introduction’s warning against needless type-level code, and chapter 12, “Custom Type Errors”; on A decision procedure and Costs and failure modes
- Pierce 2002, Types and Programming Languages – chapter 1 counts type systems among the lightweight formal methods, at the opposite end of the spectrum from Hoare logic and other heavyweight verification frameworks; on The cost of stronger guarantees
- Slatkin 2019, Effective Python, 2nd Edition – Item 90, “Consider Static Analysis via typing to Obviate Bugs”: where to add type hints first; on A decision procedure
- Wlaschin 2018, Domain Modeling Made Functional – chapter 5, “Modeling Unknown Types”:
type Undefined = exnas a placeholder that compiles until a function needs the real type; on Costs and failure modes
Further reading:
- Mak 2026, Software Design for Python Programmers – section 6.3, “Programming by contract helps eliminate surprises”: a worked
CircularBufferwith method preconditions, postconditions and a class invariant asserted after construction and every mutating method, though temporarily broken mid-mutation; on Types, contracts, runtime checks and tests - Nielson et al. 1999, Type and Effect Systems – sections 1, 3 and 4: type-and-effect judgements
Γ ⊢ e : τ & φfor side-effect and region analysis, and causal behaviours ordering channel sends and receives in Concurrent ML; on theoperation can perform IOandnetwork protocol orderingrows in A good type-system target - Rondon et al. 2008, Liquid Types – sections 1 and 5: inferred
0 <= v && v < len arefinements cut manual annotation from 31% of program text to under 1% on array-bounds benchmarks, while public library interfaces still require explicit specifications; on the0 <= x < nrow in A good type-system target and The cost of stronger guarantees - Siek et al. 2006, Gradual Typing for Functional Languages – sections 1, 2 and 5: migrating between dynamic
?and static types within one program, with compiler-inserted casts enforcing contracts at typed-untyped boundaries and pay-as-you-go runtime cost; on Types, contracts, runtime checks and tests and A decision procedure - Brooker et al. 2024, Systems Correctness Practices at AWS – “The P Programming Language”, “Lightweight Formal Methods” and “Formal Proof”: state-machine model checking in P, post-hoc log validation with PObserve, deterministic simulation and fault injection alongside Dafny and Kani proofs at critical security boundaries; on A good type-system target and The cost of stronger guarantees
- Hawblitzel et al. 2015, IronFleet: Proving Practical Distributed Systems Correct – sections 1, 4 and 7.1: proving both safety and “eventually receives a reply” liveness of distributed systems in Dafny by combining Floyd-Hoare verification with embedded TLA, at 3.6 lines of proof per line of implementation and 3.7 person-years; on A good type-system target and The cost of stronger guarantees