Chapter 6

Declare, Don't Instruct

The best code is the code the platform writes for you.
Demo: Format a currency input: imperative JS vs genX attributes
☠ Imperative: 73 lines of JavaScript
Lines executed: 0
✦ Declarative: 6 HTML attributes
Attributes scanned: 0
0
Lines of code
0
Lines of code
0
DOM API calls
0
DOM API calls

What you just saw

The left panel is imperative JavaScript that formats a currency input field. It queries the DOM for the element, attaches an event listener, parses the input string, strips non-numeric characters, handles edge cases for decimal precision, formats with locale-aware thousands separators, updates the DOM, positions the cursor, and manages focus/blur states. Seventy-three lines of instructions that tell the browser exactly how to accomplish the formatting, step by step.

The right panel is the same behavior expressed as HTML attributes. The genX library reads six attributes from the element, infers the intended behavior, and generates the same formatting logic internally. The developer declared what the input should do. The platform decided how.

The declarative version is not shorter because it does less. It is shorter because the developer specified the outcome and the platform handled the implementation. The 73 lines of imperative code still exist; they run inside genX, tested once, correct everywhere. The developer's surface area shrank from 73 lines to 6 attributes. Fewer lines means fewer bugs, because every line you write is a line that can be wrong.

How this works: This demo visualizes code volume, not timing. The imperative side requires 73 lines of JavaScript and 12 DOM API calls. The declarative side achieves the same behavior in 6 lines of HTML attributes. Line counts are from real code. Source: github.com/adamzwasserman/honest-code-traces
← Ch.5: State Has an Address Ch.7: Compose Flat, Never Deep →