Type-State Builders
Encode validity in the type system.
The Problem with Plain Builders
A normal builder lets you call build() at any time, even before required fields are set. Missing data then surfaces as a runtime panic or an Err.
Type-state builders push that check to compile time: forgetting a required step simply fails to compile.
Encoding State in Types
The trick is to make the builder generic over marker types that represent which steps are done. As you set each field, the builder's type changes.
Only when every required marker reaches its "set" state does a build() method become available.
struct Missing;
struct Set;All lessons in this course
- The Builder Pattern
- The Newtype Pattern
- Type-State Builders
- Deref and Wrapper Ergonomics