20

Replace Derived Variable with Query


Goal

Values computed from other state are computed on demand; no separate field needs to be kept in sync.

Before the refactoring
class Order {
  items;
  total;
  add(item) { this.items.push(item); this.total += item.price; }
}
After the refactoring
class Order {
  items;
  add(item)  { this.items.push(item); }
  total()    { return this.items.reduce((s, i) => s + i.price, 0); }
}
Savings

Mutation scope shrinks; reasoning about state is simpler; no chance of the derived field drifting from its source.

Note

If the derivation is expensive and the source rarely changes, recomputing on every read may be wasteful — measure before deciding.