Passing a Dependency as an Argument

An argument can supply an operation or resource a function depends on, making that dependency explicit and replaceable for testing.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Make time controllable
  2. Choose the smallest interface
  3. Control a dependency that normally changes between runs
  4. Give the dependency a narrow, realistic interface

Make time controllable

A reminder check can receive a clock function or a supplied date. A test can return a fixed date without changing the computer's clock. An outer entry point can choose the real dependency for normal execution.

Choose the smallest interface

If the reminder rule needs one instant, accept that instant. If the function needs multiple time readings, a clock interface may be useful. A function contract can define whether readings are captured once or expected to advance during the call.[1][2]

Control a dependency that normally changes between runs

Imagine checking whether a permit expires at noon. Supplying a clock whose now() method returns a fixed instant lets a test distinguish 11:59:59, 12:00:00 and 12:00:01 without waiting. Decide whether the exact expiry is already invalid. Pass a single instant if the calculation needs one reading. Pass a clock only if several readings have distinct meaning. This changes how clearly the caller can see the function's requirements. See pure functions and predictable results.

Give the dependency a narrow, realistic interface

A helper that only loads an item by ID can accept a lookup function instead of an entire repository object. Its test substitute should represent documented outcomes, such as an item with a valid ID, no record, and an error the caller may need to handle. If the real lookup can return a result representing absence, a substitute that always raises on absence can hide a contract mismatch. Include an integration check for the adapter. See returning failures or raising exceptions.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Execution Model ↩