03

Extract Variable


Goal

A complex expression earns a name that says what it represents in the domain.

Before the refactoring
if (order.qty * order.price - Math.max(0, order.qty - 500) * order.price * 0.05 > 1000) { /* ... */ }
After the refactoring
const basePrice = order.qty * order.price;
const discount  = Math.max(0, order.qty - 500) * order.price * 0.05;
if (basePrice - discount > 1000) { /* ... */ }
Savings

Reusable in nearby code; debugging shows the intermediate value; comments explaining the expression become unnecessary.

Note

Over-extracting tiny expressions clutters scope with one-shot names; extract when the expression carries domain meaning the surrounding code can't speak.