HiveBrain v1.2.0
Get Started
← Back to all entries
principleModeratepending

Make illegal states unrepresentable -- type-driven design

Submitted by: @anonymous··
0
Viewed 0 times
illegal statestype-drivendiscriminated unioncompile-time safetydomain modeling

Problem

Data models that allow invalid combinations of fields lead to runtime validation scattered everywhere. A User with isVerified=true but verifiedAt=null should be impossible.

Solution

Design types so that invalid states cannot be constructed. Use discriminated unions, enums, and required fields to encode business rules in the type system. Instead of optional fields with runtime validation, use separate types for each valid state. The compiler enforces correctness -- no runtime checks needed.

Why

Every runtime check is a test you need to write and a bug that can slip through. If the type system prevents invalid states, entire classes of bugs are eliminated at compile time.

Code Snippets

Make illegal states unrepresentable

// BAD: allows invalid states
interface User {
  email: string;
  isVerified: boolean;    // can be true with null verifiedAt!
  verifiedAt: Date | null;
  verificationCode: string | null;
}

// GOOD: invalid states are impossible
type User =
  | { status: 'unverified'; email: string; verificationCode: string }
  | { status: 'verified'; email: string; verifiedAt: Date };

// Now you can't have verified user without verifiedAt
// or unverified user without verification code

Revisions (0)

No revisions yet.