Track 04 · Lesson 13 of 15Code that stays easy to change
- 01Principles at a glance
- 02SOLID principles at a glance
- 03S: Single responsibility
- 04O: Open/closed
- 05L: Liskov substitution
- 06I: Interface segregation
- 07D: Dependency inversion
- 08Separation of concerns
- 09DRY: Don't repeat yourself
- 10KISS: Keep it simple
- 11YAGNI: You aren't gonna need it
- 12Composition over configuration
- 13Fail fast
- 14Least surprise
- 15When they disagree
Track 04 · Code that stays easy to change
Fail fast
Lesson 13 of 15· 6 min
Catch bad data as early as possible, and stop with an error that says exactly what's wrong.
Send a broken response
Pick a payload, send it, flip the switch
[
{
"id": "a1",
"name": "Tote bag",
"price": "19.99"
},
{
"id": "b2",
"name": "Mug",
"price": "19.99"
}
]API response
fetch("/api/cart")
Boundary
as CartItem[]
Cart store
useCart
Cart total
items.reduce()
Checkout screen
<CartTotal />
type CartItem = { id: string; name: string; price: number };
export async function loadCart() {
const res = await fetch("/api/cart");
// We tell TypeScript it's CartItem[]. Nobody actually checked.
const items = (await res.json()) as CartItem[];
useCart.setState({ items });
}
// …three components later, in CartTotal.tsx
const total = items.reduce((sum, i) => sum + i.price, 0);
// If price arrived as "19.99", this is string concatenation:
// 0 + "19.99" + "19.99" === "019.9919.99"Why the bug traveled so far#
as CartItem[] doesn't check anything. It tells TypeScript "trust me", and TypeScript does. So the strings sailed through the store and the total calculation, where JavaScript happily joined "19.99" + "19.99" as text, and only a human looking at the checkout screen could tell something was wrong.
Check at the boundary#
Data from outside your code, like API responses, form input, URL parameters or local storage, should be checked the moment it enters. A schema library like Zod turns the check into one line: CartItem.array().parse(json). Bad data stops right there, with an error that names the exact field. Everything after the boundary can trust what it gets.
This is the same idea as Never trust the browser, pointed the other way: your server shouldn't trust clients, and your client shouldn't blindly trust APIs.
Check yourself