Giving a Helper a Focused Responsibility
A focused helper performs work that can be described, tested, and reused with a small set of inputs.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Identify a separable calculation
An invoice command may load rows, calculate sales tax, and write a report. A helper can calculate tax from the relevant amount and rate. Tests then cover rounding without accessing files. This keeps the calculation close to a pure function.
Preserve policy names
If a new helper is called process and takes six unrelated arguments, its contract is hard to infer. A name such as tax_for_line indicates what to supply and what to expect. Add a contract for units and rounding.[1][2]
Separate changeable rules in a concrete example
An order summary turns order lines into a subtotal and presents the subtotal using the reader's currency format. A new rounding policy changes the amount calculation. A new locale changes decimal separators without changing the underlying amount. A helper returning the numeric subtotal makes these two changes independently testable. A formatting helper can still accept the amount and locale together as part of one presentation responsibility. See returning versus printing.
Keep an invariant inside the operation that owns it
Breaking one operation into helpers can make its state harder to follow if each helper mutates a shared object. For example, validating an address and replacing its previous value may belong to one public update that promises no mutation on failure. Extract a pure validator if it is useful on its own and keep the decision to commit in the update operation. Test an invalid address after an existing valid value is set. See function side effects.