A named box of code

Think of it when you decide where a piece of code should live and what to name it, or you are about to paste the same code again.

In everyday life

A kitchen keeps one recipe card for its house sauce, and every cook uses it. If each cook kept a private copy, a change to the recipe would reach some plates and miss others.

One case

A shop’s phone app works out sales tax in 4 places: the cart, the checkout, the receipt and the refund screen. Each place has its own pasted copy of the math. On 1 July the rate goes from 8% to 9%. A developer updates 3 copies and misses the fourth. Refunds still use 8%, so a customer who paid $109 for a $100 order gets $108 back.

The rate changed in 3 of 4 pasted copies
The case, cell by cell1 cell = 1 screen
Tax rate the law sets
9%9%9%9%
Tax rate in that screen's copy
9%9%9%8%
Copies missed
1
Short on a $100 refund
$1
With one tax module, the change would have been one edit.

Every case

Code that does one job should live in one place, under one name. Then a change to that job is one edit, and every place that calls it gets the change. Pasted copies drift apart: each copy is one more place to forget. A good name also lets a reader skip the inside, because the name already says what the code does.

The word

Engineers call this

function, moduleA piece of code with a name, one job, and an outside that other code uses. A functionA named piece of code that takes inputs, does one job and gives back a result, such as total(cart). is the smallest kind; a file, a package or a whole service can be one too.

Give each job one named home, and call it from everywhere that needs it. When you are about to paste the same logic again, make a home for it instead.

Where this idea leads

Skills that encode it

  • codebase-design Matt PocockA module is anything with an interface and an implementation; locality means a change concentrates in one place: fix once, fixed everywhere.
  • code-review Matt PocockFlags Duplicated Code, the same logic shape in more than one file, and says to extract the shared shape and call it from both.
  • principle-laziness-protocol pstackConsolidate decisions: do not repeat the same choice in several places; put it behind one source of truth.