Track 04 · Lesson 10 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
KISS: Keep it simple
Lesson 10 of 15· 5 min
Choose the plainest solution that solves the actual problem.
Follow one click
Toggle the sidebar in both versions
- onClick
- bus.emit()
- bus listener
- dispatch(TOGGLE)
- reducer
- context value
- useSidebarState()
- <Sidebar> renders
7
Hops from click to sidebar
5
Files to read to follow it
Seven hops across five files. Each hop is a place for a bug to hide, like a listener that subscribes twice.
// sidebar-events.ts
export const bus = new EventEmitter<{ "sidebar:toggle": void }>();
// SidebarProvider.tsx
type Action = { type: "TOGGLE" } | { type: "SET"; open: boolean };
function reducer(state: { open: boolean }, action: Action) {
switch (action.type) {
case "TOGGLE": return { open: !state.open };
case "SET": return { open: action.open };
}
}
export function SidebarProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, { open: false });
useEffect(() => bus.on("sidebar:toggle", () => dispatch({ type: "TOGGLE" })), []);
return <SidebarContext.Provider value={state}>{children}</SidebarContext.Provider>;
}
// useSidebarState.ts
export const useSidebarState = () => useContext(SidebarContext).open;
// MenuButton.tsx
<Button onClick={() => bus.emit("sidebar:toggle")}>Menu</Button>Count the hops#
Every step between cause and effect is somewhere a bug can hide and somewhere a reader has to look. The clever version takes seven hops across five files to open a sidebar. The simple one takes two, in one file you can read top to bottom.
Clever code usually comes from good intentions: "we might need other things to toggle the sidebar", "this is how big apps do it". But the tools that make large apps manageable, like event buses, global stores and dependency injection, are overhead in a small one.
Simple isn't the same as easy#
Simple means few moving parts. Sometimes that takes more thought than the clever version: finding the one useState that replaces a whole architecture is real design work.
Check yourself