09

Combine Functions into Class


Goal

Functions that all act on the same data live alongside it as methods; calls become method calls on a domain object.

Before the refactoring
function baseCharge(reading)    { /* uses reading */ }
function taxableCharge(reading) { /* uses reading */ }
After the refactoring
class Reading {
  baseCharge()    { /* ... */ }
  taxableCharge() { /* ... */ }
}
Savings

Encapsulation tightens; tests target the class; new operations land in one obvious place.

Note

Wrapping passive data in a class that nobody else uses adds ceremony — only combine when 2+ functions take the same data and would benefit from co-located behavior.