How I Made Your Machine
*A guide to writing software for humans and agents: the story of how I made your machine.*
Agent Usage
- Read this guide before implementing, refactoring, or reviewing code.
- Treat these rules as defaults unless the user requests a different tradeoff.
- Model finite values and mutually exclusive states with explicit variants/enums/unions.
- Prefer domain-specific types and function signatures over generic primitives.
- Preserve behavior-first testing: test business outcomes, not framework internals or third-party behavior.
- Call out justified exceptions explicitly when constraints force weaker typing or non-ideal structure.
- Keep unrelated code unchanged; apply the guide to the task scope instead of broad rewrites.
Agent Workflow
- Identify which sections below apply to the current task.
- Implement or refactor using the relevant patterns.
- Review the result against the Core Principles and Type Design Signals.
- Explain key changes in terms of maintainability, type safety, and behavior correctness.
Purpose
This guide lays out how we should write code for maintainability, type safety, and behavior-first testing across projects. It sets strong defaults, with room for justified exceptions when the tradeoff is clear.
Core Principles
- Make invalid states hard to represent.
- Model domain concepts explicitly instead of using ad-hoc primitives.
- Use the type system and compiler as first-line quality gates.
- Optimize for readable intent over clever implementation.
- Parse external input into domain types at system boundaries; trust refined types downstream.
- Test business behavior rather than framework or library internals.
Type Safety and Relying on the Compiler
Using a type-safe language is not enough on its own. We have to be intentional about how we model data and behavior so the compiler and static analysis can do real work for us. It is easy to write code that technically type-checks while still side-stepping most of those guarantees.
Here are some patterns that are useful to follow:
- Prefer domain types over raw strings and loosely typed containers.
- Use unions/enums/typed variants when valid values are finite.
- Favor exhaustive pattern matching where possible.
- Represent unknown external values explicitly (
Unknown*) instead of falling back silently. - Avoid weakening types (
any, broad casts, untyped flows) unless unavoidable. - Prefer functions that return refined types over void-returning validation that discards what it learns.
- Avoid duplicating the same fact across multiple fields or structures; keep one source of truth.
Type Design Signals
- If the value set is finite, use a union/enum instead of
string. - If states are mutually exclusive, use one state union/enum instead of multiple booleans.
- If function inputs represent domain concepts, use those domain types directly.
- If a function validates a condition and returns void, it is probably discarding information — return a refined type instead.
- If the same value is stored in two places, one will eventually be wrong — derive it or pick a single owner.
Example 1: Finite Value Set as Variants
Under-modeled:
status: string
Better modeled:
Status = "draft" | "published" | "archived"
status: Status// Bad: unconstrained string allows invalid values.
const underModeledStatus: string = "draff";
// Good: finite union prevents invalid states.
type Status = "draft" | "published" | "archived";
const modeledStatus: Status = "draft";// Bad: free-form string can carry invalid values.
let under_modeled_status = "draff";
// Good: enum constrains the value set.
enum Status {
Draft,
Published,
Archived,
}
let modeled_status = Status::Draft;
let _ = (under_modeled_status, modeled_status);# Bad: unconstrained string allows invalid values.
under_modeled_status: str = "draff"
# Good: StrEnum constrains valid values.
from enum import StrEnum
class Status(StrEnum):
DRAFT = "draft"
PUBLISHED = "published"
ARCHIVED = "archived"
modeled_status: Status = Status.DRAFTExample 2: Boolean Combinations to State Variants
Under-modeled:
is_draft: boolean
is_published: boolean
is_archived: boolean
Better modeled:
ContentState = "draft" | "published" | "archived"
content_state: ContentState// Bad: boolean combinations allow impossible states.
const isDraft = true;
const isPublished = true;
const isArchived = false;
// Good: one variant encodes one valid state.
type ContentState = "draft" | "published" | "archived";
const contentState: ContentState = "published";
void [isDraft, isPublished, isArchived];// Bad: booleans can contradict each other.
struct UnderModeledContentState {
is_draft: bool,
is_published: bool,
is_archived: bool,
}
// Good: enum enforces one state at a time.
enum ContentState {
Draft,
Published,
Archived,
}
let under_modeled_content_state = UnderModeledContentState {
is_draft: true,
is_published: true,
is_archived: false,
};
let modeled_content_state = ContentState::Published;
let _ = (
under_modeled_content_state.is_draft,
under_modeled_content_state.is_published,
under_modeled_content_state.is_archived,
modeled_content_state,
);# Bad: booleans can represent impossible combinations.
is_draft = True
is_published = True
is_archived = False
# Good: Literal constrains to one valid state.
from typing import Literal
ContentState = Literal["draft", "published", "archived"]
content_state: ContentState = "published"
_ = (is_draft, is_published, is_archived, content_state)Example 3: Functions Consume Domain Types
Under-modeled:
schedule_message(channel: string, is_immediate: boolean, is_scheduled: boolean)
Better modeled:
Channel = "email" | "sms" | "push"
DeliveryMode = "immediate" | "scheduled"
schedule_message(channel: Channel, delivery_mode: DeliveryMode)// Bad: primitives hide domain intent and allow contradictions.
function scheduleMessageUnderModeled(
channel: string,
isImmediate: boolean,
isScheduled: boolean,
): void {
void [channel, isImmediate, isScheduled];
}
// Good: explicit domain types make valid states clear.
type Channel = "email" | "sms" | "push";
type DeliveryMode = "immediate" | "scheduled";
function scheduleMessage(channel: Channel, deliveryMode: DeliveryMode): void {
void [channel, deliveryMode];
}// Bad: primitives allow invalid channels and conflicting mode flags.
fn schedule_message_under_modeled(channel: &str, is_immediate: bool, is_scheduled: bool) {
let _ = (channel, is_immediate, is_scheduled);
}
// Good: domain enums constrain function inputs.
enum Channel {
Email,
Sms,
Push,
}
enum DeliveryMode {
Immediate,
Scheduled,
}
fn schedule_message(channel: Channel, delivery_mode: DeliveryMode) {
let _ = (channel, delivery_mode);
}# Bad: primitive inputs accept invalid values and contradictory flags.
def schedule_message_under_modeled(
channel: str,
is_immediate: bool,
is_scheduled: bool,
) -> None:
_ = (channel, is_immediate, is_scheduled)
# Good: domain literals constrain allowed values.
from typing import Literal
Channel = Literal["email", "sms", "push"]
DeliveryMode = Literal["immediate", "scheduled"]
def schedule_message(channel: Channel, delivery_mode: DeliveryMode) -> None:
_ = (channel, delivery_mode)Parse at Boundaries
Validation checks a condition and throws or returns nothing. Parsing checks the same condition but returns a refined type that carries the proof forward. When we validate and discard what we learned, every downstream function has to re-check or trust blindly. Alexis King's Parse, Don't Validate describes this well and clearly. The full article is included as a reference.
Parse external input at system boundaries — user input, API responses, config files, webhook payloads — then pass the refined type through the rest of the system. Avoid scattering validation logic across business code (sometimes called "shotgun parsing"), where invalid input may be partially processed before being rejected. Example 12 in Exceptions shows a real-world instance of this pattern for partner webhooks.
Example 4: Return a Refined Type Instead of Void
Validation (discards knowledge):
validate_email(input: string) -> void # throws on failure
send_welcome(email: string) # must trust caller or re-check
Parsing (preserves knowledge):
parse_email(input: string) -> Email # returns proof or error
send_welcome(email: Email) # type guarantees validity// Bad: validates but returns void — caller still holds a raw string.
function validateEmail(input: string): void {
if (!input.includes("@")) {
throw new Error("invalid email");
}
}
function sendWelcomeUnderModeled(email: string): void {
validateEmail(email);
// email is still string — nothing prevents passing an unchecked value.
void email;
}
// Good: parse once at the boundary, carry proof in the type.
type Email = string & { readonly __brand: "Email" };
function parseEmail(input: string): Email {
if (!input.includes("@")) {
throw new Error("invalid email");
}
return input as Email;
}
function sendWelcome(email: Email): void {
// No re-validation needed — the type proves it was parsed.
void email;
}// Bad: validates but returns nothing — caller still holds a raw &str.
fn validate_email(input: &str) {
if !input.contains('@') {
panic!("invalid email");
}
}
fn send_welcome_under_modeled(email: &str) {
validate_email(email);
// email is still &str — nothing prevents passing an unchecked value.
let _ = email;
}
// Good: parse once at the boundary, carry proof in the type.
struct Email(String);
impl Email {
fn parse(input: &str) -> Result<Self, String> {
if !input.contains('@') {
return Err(format!("invalid email: {input}"));
}
Ok(Self(input.to_owned()))
}
}
fn send_welcome(email: &Email) {
// No re-validation needed — the type proves it was parsed.
let _ = email;
}
let _ = (send_welcome_under_modeled as fn(&str), send_welcome as fn(&Email));# Bad: validates but returns None — caller still holds a raw str.
def validate_email(input: str) -> None:
if "@" not in input:
raise ValueError("invalid email")
def send_welcome_under_modeled(email: str) -> None:
validate_email(email)
# email is still str — nothing prevents passing an unchecked value.
_ = email
# Good: parse once at the boundary, carry proof in the type.
from typing import NewType
Email = NewType("Email", str)
def parse_email(input: str) -> Email:
if "@" not in input:
raise ValueError("invalid email")
return Email(input)
def send_welcome(email: Email) -> None:
# No re-validation needed — the type proves it was parsed.
_ = emailExample 5: Smart Constructors for Non-Structural Invariants
When an invariant cannot be captured by a union or enum — like a numeric range, a non-empty list, or a formatted string — use an opaque type with a constructing function that enforces the constraint. Downstream code receives the refined type and never needs to re-validate.
Under-modeled:
percentage: number # caller must remember 0-100
Better modeled:
Percentage = opaque(number) # only created through constructor
make_percentage(n: number) -> Percentage | error// Bad: raw number allows out-of-range values.
function applyDiscountUnderModeled(percentage: number): void {
void percentage; // nothing prevents 150 or -3
}
// Good: branded type enforces range at construction.
type Percentage = number & { readonly __brand: "Percentage" };
function makePercentage(value: number): Percentage {
if (value < 0 || value > 100) {
throw new RangeError(`percentage out of range: ${value}`);
}
return value as Percentage;
}
function applyDiscount(percentage: Percentage): void {
// Safe to use directly — construction guarantees 0-100.
void percentage;
}// Bad: raw f64 allows out-of-range values.
fn apply_discount_under_modeled(percentage: f64) {
let _ = percentage; // nothing prevents 150.0 or -3.0
}
// Good: newtype with a constructor enforces the range.
struct Percentage(f64);
impl Percentage {
fn new(value: f64) -> Result<Self, String> {
if !(0.0..=100.0).contains(&value) {
return Err(format!("percentage out of range: {value}"));
}
Ok(Self(value))
}
fn value(&self) -> f64 {
self.0
}
}
fn apply_discount(percentage: &Percentage) {
// Safe to use directly — construction guarantees 0-100.
let _ = percentage.value();
}
let _ = apply_discount_under_modeled;# Bad: raw float allows out-of-range values.
def apply_discount_under_modeled(percentage: float) -> None:
_ = percentage # nothing prevents 150.0 or -3.0
# Good: NewType + constructor enforces the range.
from typing import NewType
Percentage = NewType("Percentage", float)
def make_percentage(value: float) -> Percentage:
if not (0 <= value <= 100):
raise ValueError(f"percentage out of range: {value}")
return Percentage(value)
def apply_discount(percentage: Percentage) -> None:
# Safe to use directly — construction guarantees 0-100.
_ = percentageSelf-Documenting Code
Self-documenting code is usually better than writing comments everywhere. Comments go stale quickly, while clear naming and structure have to evolve with the program.
- Prefer descriptive, domain-aligned names even when verbose.
- Keep function and type names intention-revealing.
- Add comments only for non-obvious decisions, invariants, or tradeoffs.
- Avoid comments that restate what code already makes obvious.
Example 6: Document the Why, Not the Obvious What
Low-value comment:
// Increment retry count
retry_count = retry_count + 1
High-value comment:
// Billing provider closes refunds at next-day midnight, so keep a one-day grace period.
refund_grace_period_days = 1
is_refund_eligible = days_since_purchase <= refund_window_days + refund_grace_period_days// Bad: restates obvious code behavior without context.
function incrementRetryCount(retryCount: number): number {
// Increment retry count.
return retryCount + 1;
}
// Good: documents a non-obvious business constraint.
function isRefundEligible(
daysSincePurchase: number,
refundWindowDays: number,
): boolean {
// Billing provider closes refunds at next-day midnight, so we keep a one-day grace period.
const refundGracePeriodInDays = 1;
return daysSincePurchase <= refundWindowDays + refundGracePeriodInDays;
}// Bad: restates obvious behavior.
fn increment_retry_count(retry_count: u32) -> u32 {
// Increment retry count.
retry_count + 1
}
// Good: documents a non-obvious business constraint.
fn is_refund_eligible(days_since_purchase: u32, refund_window_days: u32) -> bool {
// Billing provider closes refunds at next-day midnight, so we keep a one-day grace period.
let refund_grace_period_in_days = 1;
days_since_purchase <= refund_window_days + refund_grace_period_in_days
}
let _ = increment_retry_count(0);# Bad: restates obvious behavior.
def increment_retry_count(retry_count: int) -> int:
# Increment retry count.
return retry_count + 1
# Good: documents a non-obvious business constraint.
def is_refund_eligible(days_since_purchase: int, refund_window_days: int) -> bool:
# Billing provider closes refunds at next-day midnight, so we keep a one-day grace period.
refund_grace_period_in_days = 1
return days_since_purchase <= refund_window_days + refund_grace_period_in_days
_ = increment_retry_count(0)Testing Business Logic First
Tests are important for verifying behavior and preventing regression at both unit and integration levels. But we should avoid writing tests for the sake of writing tests: they add maintenance cost and create noise when they assert outcomes that do not matter to business behavior.
- Test business outcomes and domain behavior first.
- Prioritize tests for state transitions, input-to-output rules, defaults, and fallback behavior.
- Do not test third-party/library internals.
- Avoid mocks by default.
- Use mocks only for unstable boundaries (network, filesystem, time, OS/process boundaries).
- Assert externally meaningful behavior, not private implementation details.
Example 7: Test State Transitions and Outcomes
Brittle:
assert transition_helper_called_once()
Behavior-focused:
result = transition_order_state("draft", "publish")
assert result == "published"import { describe, expect, it } from "vitest";
describe("transitionOrderStateUnderTest", () => {
it("bad: asserts an implementation detail", () => {
const transitionHelperCallCount = 1;
expect(transitionHelperCallCount).toBe(1);
});
});
describe("transitionOrderState", () => {
it("good: asserts observable state transition", () => {
const nextState = transitionOrderState("draft", "publish");
expect(nextState).toBe("published");
});
});#[test]
fn bad_asserts_implementation_detail_only() {
let transition_helper_call_count = 1;
assert_eq!(transition_helper_call_count, 1);
}
#[test]
fn good_transitions_draft_to_published_when_publish_is_requested() {
let next_state = transition_order_state("draft", "publish");
assert_eq!(next_state, "published");
}def test_bad_asserts_implementation_detail_only() -> None:
transition_helper_call_count = 1
assert transition_helper_call_count == 1
def test_good_transition_order_state_moves_draft_to_published() -> None:
next_state = transition_order_state("draft", "publish")
assert next_state == "published"Example 8: Mock Only Unstable Boundaries
Preferred:
fake_clock = FixedClock("2025-01-01T00:00:00Z")
assert discount_is_active(fake_clock)
Avoid:
assert internal_helper_called("calculate_discount_window")import { expect, it, vi } from "vitest";
it("bad: mocks an internal helper and asserts internals", () => {
const calculateDiscountWindow = vi.fn().mockReturnValue(true);
calculateDiscountWindow();
expect(calculateDiscountWindow).toHaveBeenCalledTimes(1);
});
it("good: mocks only unstable network boundary and asserts behavior", async () => {
const fetchExchangeRate = vi.fn().mockRejectedValue(new Error("timeout"));
const gateway = createCurrencyGateway({ fetchExchangeRate });
const rate = await gateway.getRateOrFallback("USD", "EUR");
expect(rate).toBe(0.92);
});#[test]
fn bad_asserts_internal_helper_behavior() {
let internal_helper_call_count = 1;
assert_eq!(internal_helper_call_count, 1);
}
#[test]
fn good_uses_cached_rate_when_live_lookup_fails() {
let gateway = CurrencyGateway::new(FailingRateClient, CachedRateStore::with_rate(0.92));
let rate = gateway.get_rate_or_fallback("USD", "EUR");
assert_eq!(rate, 0.92);
}def test_bad_asserts_internal_helper_behavior() -> None:
internal_helper_call_count = 1
assert internal_helper_call_count == 1
def test_good_uses_cached_rate_when_live_lookup_fails() -> None:
gateway = CurrencyGateway(
rate_client=FailingRateClient(),
cache_store=CachedRateStore(rate=0.92),
)
rate = gateway.get_rate_or_fallback("USD", "EUR")
assert rate == 0.92Choosing Dependencies
The code we import carries the same maintenance cost as code we write. A dependency is a commitment to its API surface, its release cadence, its transitive dependencies, and its type design choices. Every dependency is also an attack surface — supply chain attacks target unmaintained, obscure, or compromised packages, so choosing well is a security concern, not just a quality one.
- Prefer popular, actively maintained libraries backed by organizations or well-known open-source communities. Recent contributions, high download counts, and security audit history all signal that vulnerabilities are more likely to be caught early.
- If two libraries solve the same problem and equally safe to depend on, prefer the one whose API returns well-typed domain objects over one that returns loosely typed containers (
any, raw dicts, untyped JSON). - Value libraries whose internals reflect stronger type design. A Python library with a Rust core benefits from Rust's compiler guarantees at the boundary while remaining ergonomic in Python.
- If the functionality is a well-known algorithm or data structure that fits in a few lines, re-implement it. The dependency's maintenance cost will exceed the code's, and every dependency you avoid is one fewer supply chain risk.
- If you would need to wrap the library in adapter types to make it fit your domain model, weigh whether the library is saving you work or creating it.
Example 10: Prefer Libraries That Align With Your Type Design
Poor alignment:
response = http_get(url) # returns untyped dict
name = response["user"]["name"] # runtime key error if shape changes
Good alignment:
response = http_get(url) -> User # returns typed domain object
name = response.name # compiler catches field typos// Bad: library returns `any` — caller must cast or assert at every access.
async function getUserNameUnderModeled(userId: string): Promise<string> {
// biome-ignore lint/suspicious/noExplicitAny: demonstrating a bad library API
const response: any = await untypedHttpClient.get(`/users/${userId}`);
return response.data.name;
}
// Good: library returns typed response — compiler catches field errors.
import { z } from "zod";
const UserSchema = z.object({
name: z.string(),
email: z.string(),
});
type User = z.infer<typeof UserSchema>;
async function getUserName(userId: string): Promise<string> {
const response = await typedHttpClient.get(`/users/${userId}`, UserSchema);
return response.name;
}use serde::Deserialize;
use serde_json::Value;
// Bad: library returns serde_json::Value — caller must chain fallible accessors.
fn get_user_name_under_modeled(response: &Value) -> Option<&str> {
response.get("user")?.get("name")?.as_str()
}
// Good: library deserializes into a typed struct — field access is compile-checked.
#[derive(Deserialize)]
struct User {
name: String,
email: String,
}
fn get_user_name(user: &User) -> &str {
&user.name
}
let _ = get_user_name_under_modeled;from typing import Any
# Bad: library returns untyped dict — field access is unchecked.
def get_user_name_under_modeled(response: dict[str, Any]) -> str:
return response["user"]["name"] # KeyError if shape changes
# Good: library returns typed model — type checker catches field errors.
from dataclasses import dataclass
@dataclass
class User:
name: str
email: str
def get_user_name(user: User) -> str:
return user.nameExample 11: Re-implement When the Dependency Outweighs the Logic
Unnecessary dependency:
import clamp from "math-utils-lib"
result = clamp(value, 0, 100)
Better as local code:
clamp(value, min, max) = max(min, min(max, value))
result = clamp(value, 0, 100)// Bad: importing a package for a one-liner adds supply-chain surface for no benefit.
// import { clamp } from "math-utils-lib";
// const clampedFromLib = clamp(value, 0, 100);
// Good: trivial, well-understood logic is cheaper to own than to import.
function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
const clamped = clamp(150, 0, 100);
void clamped;// Bad: pulling in an external crate for something the standard library already provides.
// use num::clamp;
// let clamped_from_crate = clamp(150.0, 0.0, 100.0);
// Good: the standard library already has f64::clamp — no dependency needed.
let clamped = 150.0_f64.clamp(0.0, 100.0);
let _ = clamped;# Bad: importing a utility library for a one-liner adds supply-chain surface for no benefit.
# from math_utils_lib import clamp
# clamped_from_lib = clamp(value, 0, 100)
# Good: trivial, well-understood logic is cheaper to own than to import.
def clamp(value: float, lo: float, hi: float) -> float:
return max(lo, min(hi, value))
clamped = clamp(150, 0, 100)For guidance on choosing linters and type checkers, see Choosing Linters and Type Checkers.
Exceptions
We can make exceptions when strict modeling creates disproportionate complexity, external contracts require looser typing, or performance/interoperability constraints apply.
When we take an exception, we should document:
- Which rule is being bent
- Why
- Which safeguards are in place (validation, logging, tests)
Example 12: External Contract Requires Looser Typing
Rule being bent:
"Finite value set -> union/enum instead of string"
Why:
Partner webhook sends undocumented status values.
Safeguards:
validate known values
map unknown values to UnknownPartnerStatus
log raw unknown values
test known and unknown inputs// Bad: assumes external input already matches strict known values.
type UnderModeledPartnerStatus = "accepted" | "rejected";
function parsePartnerStatus(rawPartnerStatus: UnderModeledPartnerStatus): UnderModeledPartnerStatus {
return rawPartnerStatus;
}
// Good: accept string input, validate known values, and map unknown values explicitly.
type KnownPartnerStatus = "accepted" | "rejected";
type PartnerStatus = KnownPartnerStatus | "unknown_partner_status";
function mapPartnerStatus(rawPartnerStatus: string): PartnerStatus {
if (rawPartnerStatus === "accepted" || rawPartnerStatus === "rejected") {
return rawPartnerStatus;
}
console.warn("unknown partner status", { rawPartnerStatus });
return "unknown_partner_status";
}// Bad: panics on unexpected partner status values.
enum UnderModeledPartnerStatus {
Accepted,
Rejected,
}
fn parse_partner_status(raw_partner_status: &str) -> UnderModeledPartnerStatus {
match raw_partner_status {
"accepted" => UnderModeledPartnerStatus::Accepted,
"rejected" => UnderModeledPartnerStatus::Rejected,
_ => panic!("unsupported partner status: {raw_partner_status}"),
}
}
// Good: capture unknown values explicitly and continue safely.
enum PartnerStatus {
Accepted,
Rejected,
UnknownPartnerStatus,
}
fn map_partner_status(raw_partner_status: &str) -> PartnerStatus {
match raw_partner_status {
"accepted" => PartnerStatus::Accepted,
"rejected" => PartnerStatus::Rejected,
_ => {
eprintln!("unknown partner status: {raw_partner_status}");
PartnerStatus::UnknownPartnerStatus
}
}
}
let _ = parse_partner_status("accepted");from typing import Literal
# Bad: assumes the partner only ever sends known values.
UnderModeledPartnerStatus = Literal["accepted", "rejected"]
def parse_partner_status(raw_partner_status: UnderModeledPartnerStatus) -> UnderModeledPartnerStatus:
return raw_partner_status
# Good: accept raw string input and map unknown values explicitly.
PartnerStatus = Literal["accepted", "rejected", "unknown_partner_status"]
def map_partner_status(raw_partner_status: str) -> PartnerStatus:
if raw_partner_status in {"accepted", "rejected"}:
return raw_partner_status
print(f"unknown partner status: {raw_partner_status}")
return "unknown_partner_status"