15.10 · Types that prevent misuse, error types for libraries, one-shot values and when to trap

The best API makes the wrong call impossible or loud. That is a choice about types, ownership and failure mode.

Mental model. Move mistakes from run time to compile time where you can, and make the remaining failures deliberate: a typed error, a nil, or a trap.

Types that guide callers

Typed identifiers and values that can be used only once.

  1. How do phantom-typed identifiers stop an order id being passed where a user id is expected, and what do they cost? 15.10.1 · L3
    Most bugs of the form “loaded the wrong thing” come from passing an Int or String id to the wrong function: every id is the same type, so the compiler cannot…
  2. How do noncopyable types and consuming methods make an API hard to misuse: transactions, tokens and one-shot handles? 15.10.2 · L5
    Some values must be used exactly once: a transaction (commit or roll back), a continuation (resume once), a file handle (close once), a one-time token. With…

How an API fails

Library error types and the trap-versus-throw decision.

  1. How do you design the error type of a library: stable cases, underlying errors, LocalizedError, and bridging to NSError? 15.10.3 · L5
    Q358 covers where to translate errors; this is about what the error type promises. A library error is part of the public API, so design it like one. Use an…
  2. When should an API trap with precondition, return nil, or throw: programmer error versus expected failure? 15.10.4 · L3
    Pick by who could have prevented the failure and whether the caller can reasonably recover. A violated precondition that the caller controls and could have…

More in Architecture & API design