HeadlinesBriefing favicon HeadlinesBriefing.com

Type-Driven Design: Parse, Don't Validate

Hacker News: Front Page •
×

Type-driven design can be difficult to explain, but a simple slogan captures its essence: Parse, don't validate. This approach emerged from comparing JSON parsing in statically and dynamically typed languages. Instead of writing functions that might fail at runtime, type-driven design uses the type system to ensure correctness at compile time.

Consider the classic `head` function that returns the first element of a list. In Haskell, the naive implementation has a critical flaw: it's partial and fails on empty lists. The compiler helpfully points out this gap, forcing developers to confront the impossibility of returning a value from nothing. The traditional fix—returning a `Maybe` type—shifts the burden to callers who must handle impossible cases.

A better solution strengthens the input type using `NonEmpty`, which guarantees at least one element. This eliminates runtime errors entirely and makes the function total. The `head` function becomes trivial to implement and provably correct. This philosophy extends beyond simple examples to complex systems where type-driven design catches errors before they reach production. By parsing inputs into precise types that encode all constraints, developers create APIs that are impossible to misuse.