king-type-driven-design
Skill1 starsChanged 37 days agoMITView on GitHub
Parse, don't validate: raw data becomes rich types at the boundary, illegal states unrepresentable, total functions. Use when designing domain types or input handling, or reviewing validation that returns booleans, scattered checks, or flag-based state.
In this repository19 other files it gives its agents.
- add-lensSkill
- dhh-majestic-monolithSkill
- fowler-evolutionary-designSkill
- ousterhout-deep-modulesSkill
- uncle-bob-solid-orthodoxSkill
- kleppmann-data-contractsSkill
- lamport-state-invariantsSkill
- carmack-inlined-executionSkill
- danluu-empirical-systemsSkill
- muratori-data-orientedSkill
- armstrong-fault-isolationSkill
- ask-councilSkill
- djb-isolated-privilegeSkill
- hickey-simple-valuesSkill
- antirez-pragmatic-cSkill
- bellard-autonomous-engineSkill
- cantrill-observability-firstSkill
- pike-unix-minimalismSkill
- stenberg-defensive-cSkill
The file
Files
Alexis King: Type-Driven Correctness & "Parse, Don't Validate"
Apply: write or review the target under Sections 2 and 3. Done when every rule is either satisfied or reported as violated, and every checklist item is marked hit (with file:line) or clear. When a rule collides with a stated requirement, name the trade-off from Section 1 rather than bending the rule silently.
1. Core Philosophy & Deliberate Rejections
- Prioritizes: "Parse, don't validate" (transforming unstructured, untrusted data at the system boundary into precise, rich types that capture and preserve verified facts throughout the program); making illegal states unrepresentable using Algebraic Data Types (ADTs); treating types as generative axioms that define what valid states exist; total functions that can never fail at runtime; and pushing uncertainty to the system perimeter.
- Rejects: Traditional validation routines that inspect data and return booleans or throw exceptions while discarding the verified knowledge (leaving downstream code to operate on raw, untrusted primitives like
StringorList); "shotgun parsing" (scattering validation checks throughout domain logic); partial functions (such asheadon potentially empty lists); stringly-typed architectures; and treating the typechecker as an adversary rather than an automated proof engine. - Primary Trade-off: Sacrifices quick untyped prototype velocity and loose primitive-based flexibility in exchange for eliminating entire classes of runtime defects (null pointer exceptions, out-of-bounds errors, malformed payloads) at compile time.
2. Hard Implementation Rules
- Rule 1 (Parse at Boundaries): Input validation MUST be structured as parsing: a function that receives raw, unverified data MUST return a refined, specialized type (e.g.,
parseEmail(string) -> Result<EmailAddress>) or fail. Functions MUST NOT validate data and then return raw untyped primitives. - Rule 2 (Make Illegal States Unrepresentable): Data structures MUST be designed so that invalid domain states cannot be constructed. Code MUST use sum types, non-empty collections (
NonEmptyList), and discriminated unions rather than multi-boolean flags that allow contradictory states. - Rule 3 (No Downstream Defensive Re-Checking): Domain and business logic MUST accept only parsed, typed domain values. Inner functions MUST NOT re-verify preconditions or perform redundant null/empty checks on values whose types already guarantee validity.
- Rule 4 (Total Functions Only): Public API functions MUST be total: they MUST produce a valid output for every conceivable input allowed by their type signature. Functions MUST NOT throw unchecked runtime errors or panics on legal type inhabitants (e.g., calling
headon an empty list). - Rule 5 (Types as Axioms): Types MUST be modeled additively as domain axioms that specify permissible operations. Developers MUST NOT rely on runtime type assertions (
as,instanceof, downcasting) to bypass static type checks.
3. Code Review Checklist
- Validation Without Refinement Smell: Does a function check if an argument is valid (e.g.,
validateUser(user)) and returnvoidorbool, leaving the caller with the same raw unvalidated type? - Shotgun Parsing: Are validation checks (e.g., string length, format regex, range checks) scattered throughout deep business logic rather than concentrated at the ingestion boundary?
- Representable Illegal State: Does a data structure contain fields that can contradict each other (e.g.,
isLoggedIn: boolalongsideuserId: Option<string>) instead of a unified tagged union? - Partial Function Warning: Is there a method that throws an exception when called with valid types (e.g., popping an empty list, indexing an unverified array)?
- Downstream Defensive Clutter: Does internal domain code repeatedly check
if (value != null && value.length > 0)instead of expecting aNonEmptyList?
4. Canonical Idiom (Reference Pattern)
REJECTED: Validation pattern discarding verified knowledge and forcing defensive checks
// REJECTED: "Validate" pattern - inspects condition, throws error, returns raw unrefined data
function validateNonEmpty(items: string[]): void {
if (items.length === 0) {
throw new Error("List cannot be empty");
}
}
// Downstream code STILL receives raw string[] and must defensively handle empty lists!
function processItems(items: string[]): string {
validateNonEmpty(items);
// Partial function: items[0] could theoretically be undefined according to the type system!
// Forces developers or linters to add redundant checks or non-null assertions (!)
return items[0].toUpperCase();
}ACCEPTED: "Parse, Don't Validate" pattern capturing proofs in the type system
// ACCEPTED: Canonical Alexis King "Parse, Don't Validate" idiom
// The type itself proves the list contains at least one element.
export type NonEmptyArray<T> = [T, ...T[]];
// Boundary Parser: transforms untrusted raw data into the refined type
export function parseNonEmpty<T>(items: T[]): NonEmptyArray<T> | null {
if (items.length === 0) {
return null; // Parsing fails cleanly at boundary
}
return [items[0], ...items.slice(1)];
}
// Downstream domain function is TOTAL: cannot fail at runtime, zero defensive checks needed!
export function processFirstItem(items: NonEmptyArray<string>): string {
// items[0] is guaranteed to exist at compile time by the type axiom.
// Illegal states (empty list) are completely UNREPRESENTABLE!
return items[0].toUpperCase();
}Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

