tech, developers, and the code underneath

issue 250· essay·

Types at the edges

Parse untrusted input once, at the boundary, into a type that cannot be wrong. Everything inside gets simpler.

There is a design rule that quietly removes a large fraction of defensive code: validate at the boundary, and represent the result as a type that cannot hold an invalid value.

The phrase people use is "parse, don't validate." Validation returns a boolean and throws away what it learned. Parsing returns a new value that carries the proof.

python
# validation: the knowledge evaporates
def is_valid_email(s: str) -> bool: ...

if is_valid_email(raw):
    send(raw)          # send() still takes a str, and still cannot trust it

# parsing: the knowledge is in the type
class Email(str):
    def __new__(cls, raw: str) -> "Email":
        if not EMAIL_RE.fullmatch(raw):
            raise ValueError(f"not an email: {raw!r}")
        return super().__new__(cls, raw)

def send(to: Email) -> None: ...   # cannot be called with an unchecked string

The second version makes the check unforgettable, because the only way to produce an Email is to go through the constructor.

where the boundary is#

Every place data enters your program from somewhere you do not control:

  • HTTP request bodies, query strings, headers
  • Environment variables and config files
  • Database rows — yes, including your own database
  • Message queue payloads
  • Third-party API responses
  • CLI arguments
  • Anything deserialised

"Including your own database" is the contentious one. Your database contains rows written by an older version of your code, by a migration, and by whoever ran that UPDATE during the incident. It is a boundary.

the shape this gives a program#

Three layers, and the middle one is where the logic lives:

  ┌─────────────────────────────────────┐
  │  edge: strings, bytes, JSON, Any    │  ← parse here, once
  ├─────────────────────────────────────┤
  │  core: only well-formed types       │  ← no validation, no None checks
  ├─────────────────────────────────────┤
  │  edge: serialise back out           │
  └─────────────────────────────────────┘

The payoff is that the core stops defending itself. No if user is None, no assert amount > 0, no re-checking the same string in four functions because nobody is sure who checked it last. Those checks disappear not because you removed them carelessly but because they became unreachable.

making illegal states unrepresentable#

The same principle applied to state:

python
# three booleans: eight states, five of them nonsense
class Order:
    is_paid: bool
    is_shipped: bool
    is_cancelled: bool

# a sum type: exactly the states that exist
Order = Draft | Paid | Shipped | Cancelled

The first version requires a comment explaining which combinations are valid, and a function to check it, and a test for the function. The second version requires nothing, because "shipped and cancelled" cannot be constructed.

Every language has a form of this. Sum types and pattern matching in Rust, Swift, Kotlin, and modern Python; discriminated unions in TypeScript; sealed classes in Java. Use them at the point where you would otherwise write a comment about which fields are set together.

the honest costs#

Boilerplate. Wrapper types need constructors and sometimes conversions. In languages without good support this is real friction. Use a library — dataclasses with validators, a schema library, whatever your ecosystem has — and reserve hand-written wrappers for the types that genuinely matter.

Error messages. Parsing at the edge means all failures surface there, so collect them rather than failing on the first one. "Three fields are invalid" is much better than three round trips.

It does not survive serialisation. The moment you write to JSON you are back to strings. That is fine — that is the boundary, and the boundary is where the parsing goes.

The goal is not more types. It is fewer places where a value could be wrong, so that the number of places you must be careful is small enough to hold in your head.

get README in your inbox

One dispatch, no noise. Tech and developer news, plus the occasional long piece on the craft.

subscribe →