Chapter 2

Classes Considered Harmful

Not because they can't work. Because they lie about what they do.
Demo: Mutation Web: addItem → applyCoupon → removeItem
☠ Dishonest: Order class (Java)
addItem()
applyCoupon()
removeItem()
Order
items[]
total0.00
discount0.00
tax0.00
couponnull
statusPENDING
updatedAtnull
recalculateTotal()
recalculateDiscount()
recalculateTax()
CouponRegistry
«singleton»
TaxService
«singleton»
✦ Honest: calculate_order (Python)
calculate_order(items, coupon, addr, rates)
total = sum(i * q for i, q)
discount = apply_coupon(...)
tax = calculate_tax(...)
return { total, discount, tax }
total89.97
discount9.00
tax6.48
grand_total87.45
0 nanoseconds later...
0
Nanoseconds (class)
0
Nanoseconds (function)
0
Field mutations
0
Singleton lookups
Speed: |

What you just saw

The left panel is a Java Order class with 7 mutable fields. Three method calls (addItem, applyCoupon, removeItem) each trigger cascading recalculations. Every recalculation mutates fields that other recalculations depend on. Two of those recalculations reach into Singleton global state: the CouponRegistry and the TaxService. Each Singleton lookup is a pointer chase across the heap, costing hundreds of nanoseconds in cache misses.

The right panel is a pure function. Data flows in at the top. Result comes out at the bottom. No fields to mutate. No Singletons to chase. No state that can change between steps. The function finished and sat idle while the class version was still chasing pointers through global mutable caches.

The nanosecond counter is the real story. The class version spends most of its time waiting on memory, not computing. Pointer chases to heap-scattered objects, Singleton lookups through cache layers, field mutations that invalidate CPU cache lines. The function version's time is almost entirely useful work: arithmetic on data already in registers.

How this works: This demo visualizes the execution difference between dishonest and honest code. Timing is proportional to real captured nanosecond costs. Instrumented source code, Dockerfile, and raw trace data: github.com/adamzwasserman/honest-code-traces
← Ch.1: All Languages are Good Ch.3: Data Is Just Data →