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.
- How do phantom-typed identifiers stop an order id being passed where a user id is expected, and what do they cost?
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… - How do noncopyable types and consuming methods make an API hard to misuse: transactions, tokens and one-shot handles?
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.
- How do you design the error type of a library: stable cases, underlying errors, LocalizedError, and bridging to NSError?
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… - When should an API trap with precondition, return nil, or throw: programmer error versus expected failure?
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
- 15.1 · MVC, MVVM, MVP, VIPER, RIBs, TCA and Clean, and unidirectional data flow
- 15.2 · Coordinators, routers and dependency injection
- 15.3 · Feature modules and boundaries, and strangling a legacy codebase
- 15.4 · throws, Result, typed throws and mapping errors at boundaries
- 15.5 · Designing a Swift API: naming, ownership, documentation and evolution
- 15.6 · SOLID without dogma, and building a platform for many apps
- 15.7 · Effects and cancellation, modelling state, composing reducers
- 15.8 · Closure-based clients, dependency lifetimes, generic repositories and building the graph lazily
- 15.9 · Binary breaks from innocent changes, and what an import exposes