Inverting Dependencies
In this pack:
sizing,
notation,
rule strictness.
Overview
Domain code should read like the clinic it serves. When a scheduler opens
a database connection or asks a global for the time, the rule it enforces
is tied to a machine, a product and a moment, and a test can run only
where those exist. This skill moves each outside system behind an
interface the domain owns, passes every collaborator in through a
constructor, and builds the whole graph once at the program's edge.
When to use
- A domain class imports a database client, a network client, a clock or
a framework type.
- A constructor creates its own collaborator, or a method fetches one
from a global, a static field or a registry.
- A test cannot check a domain rule without a running database, a
network or the real clock.
- A program has no single place where its objects are built and
connected.
- A framework creates the program's objects, and domain classes carry
its markers or extend its base classes.
- The same object is built in several places with slightly different
collaborators.
When not to use
- The dependency is a value or a stable library with no side effects,
such as date arithmetic: depend on it directly.
- The question is which part of a design varies and deserves a seam at
all:
encapsulating what varies
decides that from evidence.
- The question is how the whole system is split into layers or modules,
not which collaborators one class receives.
- An object can exist half-built or needs setup calls after its
constructor:
constructing valid objects
covers that case.
Core rules
Rule. Put the interface the domain needs beside the domain, as a
port, and let an adapter answer it. The class that holds the rule
names the messages it sends, such as Appointments.add, never the
database type behind them. An adapter that talks to a database, a
clock, a network or a framework answers those messages and keeps the
outside details. The domain can then be built and exercised with no
outside system running.
Rule. Pass every collaborator to its object through the
constructor. A collaborator the object could be handed is not built
inside it, fetched from a registry, or read from a static field. The
parameter list then says what the object needs, a missing part stops
the object at construction, and a test can supply a stand-in. A part
whose lifetime the object owns, such as a schedule's slots, is still
created by it.
Rule. Construct and connect the object graph in one place at the
program's edge: the composition root. The entry script or the start
of a request creates the adapters and gives them to the objects that
use them. An adapter's name appears only in that root; no domain class
constructs one.
Default. Write the composition root by hand as plain constructor
calls, each one after the objects it needs. A missing collaborator
then stops the program at start-up instead of during a booking, and
the root reads as a map of the program.
The exception is a framework that builds its own objects, such as
request handlers. Give that framework the choices the root made, and
keep its markers and base classes off domain classes.
Rule. Do not hand a service locator or a container to domain
code. When a class asks a locator for its collaborators, the
constructor no longer says what the class uses, the failure waits
until a message runs, and each test must set up the locator before it
can check a rule.
Judgement. Take the port's shape from the domain's need, not from
the outside library's own methods, and add the port only where the
outside side varies, takes time, or is awkward to control in a test.
The outside side's behaviour decides: a database, a clock, a message
queue or a mail server earns a port, while pure date arithmetic and
other stable, side-effect-free libraries are called directly.
Pattern
Before, AppointmentScheduler creates a ClinicDatabase in its
constructor and keeps the database type in its field. It cannot run
without a database, and no test can put a stand-in in its place. book
still sends Appointment.book to reserve the slot, so the domain rule
stays where it was.
Before:
class ClinicDatabase
+ insert(appointment: Appointment): void
class AppointmentScheduler
- database: ClinicDatabase
+ new()
database := new ClinicDatabase()
+ book(slot: Slot, patient: PatientId): void
appointment := Appointment.book(slot, patient)
database.insert(appointment)
return
ClinicDatabase.insert is taken to store one appointment once.
After:
interface Appointments
+ add(appointment: Appointment): void
class DatabaseAppointments implements Appointments
- database: ClinicDatabase
+ new(database: ClinicDatabase)
+ add(appointment: Appointment): void
database.insert(appointment)
return
class AppointmentScheduler
- appointments: Appointments
+ new(appointments: Appointments)
+ book(slot: Slot, patient: PatientId): void
appointment := Appointment.book(slot, patient)
appointments.add(appointment)
return
class ClinicApp
+ static start(database: ClinicDatabase): AppointmentScheduler
return new AppointmentScheduler(
new DatabaseAppointments(database))
After, AppointmentScheduler holds the port and receives it through its
constructor. DatabaseAppointments adapts ClinicDatabase to that port,
and a call to Appointments.add is taken to store one appointment once.
ClinicApp.start is the composition root: it receives the open
database, builds the adapter once and the scheduler once, and is the
only place that names the adapter. The entry script opens the database
and passes it to start. Appointment.book is sent, not redeclared.
Red flags
Places to look, not verdicts. A red flag becomes a finding only with
evidence: a measurement, a reproducible bug, or a failing test.
- A domain class that imports a database, network, file or framework
type.
- A constructor that creates its own collaborators with
new.
- A static or global lookup for a collaborator inside a method.
- A test that needs a running database, a network or the real clock to
check a domain rule.
- Object creation scattered across many classes instead of one root.
- A constructor that takes a locator or a container instead of the
collaborators it uses.
Common mistakes
- An interface for every class, including values and stable libraries
with no side effects.
- A port that copies the outside library's methods, so the domain still
speaks the library's terms.
- Passing the container itself into constructors, which is a service
locator by another name.
- A composition root that also holds domain rules.
- Putting a framework's markers on domain classes so the framework can
create them.
- Building the same object in two places, so the program has two graphs
that drift apart.
Related skills
Further reading
- Ports and adapters
- Composition roots
1---2name: oo-inverting-dependencies3description: Use when domain code depends on a database, framework or clock, when an object builds or looks up its collaborators, or when wiring objects.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-inverting-dependencies7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Inverting Dependencies1213**In this pack:**14[sizing](../oo-design/SKILL.md#how-much-design-a-task-warrants),15[notation](../oo-design/references/notation.md),16[rule strictness](../oo-design/SKILL.md#how-strictly-a-rule-is-meant).1718## Overview1920Domain code should read like the clinic it serves. When a scheduler opens21a database connection or asks a global for the time, the rule it enforces22is tied to a machine, a product and a moment, and a test can run only23where those exist. This skill moves each outside system behind an24interface the domain owns, passes every collaborator in through a25constructor, and builds the whole graph once at the program's edge.2627## When to use2829- A domain class imports a database client, a network client, a clock or30 a framework type.31- A constructor creates its own collaborator, or a method fetches one32 from a global, a static field or a registry.33- A test cannot check a domain rule without a running database, a34 network or the real clock.35- A program has no single place where its objects are built and36 connected.37- A framework creates the program's objects, and domain classes carry38 its markers or extend its base classes.39- The same object is built in several places with slightly different40 collaborators.4142## When not to use4344- The dependency is a value or a stable library with no side effects,45 such as date arithmetic: depend on it directly.46- The question is which part of a design varies and deserves a seam at47 all:48 [encapsulating what varies](../oo-encapsulating-what-varies/SKILL.md)49 decides that from evidence.50- The question is how the whole system is split into layers or modules,51 not which collaborators one class receives.52- An object can exist half-built or needs setup calls after its53 constructor:54 [constructing valid objects](../oo-constructing-valid-objects/SKILL.md)55 covers that case.5657## Core rules58591. Rule. **Put the interface the domain needs beside the domain, as a60 port, and let an adapter answer it.** The class that holds the rule61 names the messages it sends, such as `Appointments.add`, never the62 database type behind them. An adapter that talks to a database, a63 clock, a network or a framework answers those messages and keeps the64 outside details. The domain can then be built and exercised with no65 outside system running.66672. Rule. **Pass every collaborator to its object through the68 constructor.** A collaborator the object could be handed is not built69 inside it, fetched from a registry, or read from a static field. The70 parameter list then says what the object needs, a missing part stops71 the object at construction, and a test can supply a stand-in. A part72 whose lifetime the object owns, such as a schedule's slots, is still73 created by it.74753. Rule. **Construct and connect the object graph in one place at the76 program's edge: the composition root.** The entry script or the start77 of a request creates the adapters and gives them to the objects that78 use them. An adapter's name appears only in that root; no domain class79 constructs one.80814. Default. **Write the composition root by hand as plain constructor82 calls, each one after the objects it needs.** A missing collaborator83 then stops the program at start-up instead of during a booking, and84 the root reads as a map of the program.8586 The exception is a framework that builds its own objects, such as87 request handlers. Give that framework the choices the root made, and88 keep its markers and base classes off domain classes.89905. Rule. **Do not hand a service locator or a container to domain91 code.** When a class asks a locator for its collaborators, the92 constructor no longer says what the class uses, the failure waits93 until a message runs, and each test must set up the locator before it94 can check a rule.95966. Judgement. **Take the port's shape from the domain's need, not from97 the outside library's own methods, and add the port only where the98 outside side varies, takes time, or is awkward to control in a test.**99 The outside side's behaviour decides: a database, a clock, a message100 queue or a mail server earns a port, while pure date arithmetic and101 other stable, side-effect-free libraries are called directly.102103## Pattern104105Before, `AppointmentScheduler` creates a `ClinicDatabase` in its106constructor and keeps the database type in its field. It cannot run107without a database, and no test can put a stand-in in its place. `book`108still sends `Appointment.book` to reserve the slot, so the domain rule109stays where it was.110111Before:112113```text114class ClinicDatabase115 + insert(appointment: Appointment): void116117class AppointmentScheduler118 - database: ClinicDatabase119 + new()120 database := new ClinicDatabase()121 + book(slot: Slot, patient: PatientId): void122 appointment := Appointment.book(slot, patient)123 database.insert(appointment)124 return125```126127`ClinicDatabase.insert` is taken to store one appointment once.128129After:130131```text132interface Appointments133 + add(appointment: Appointment): void134135class DatabaseAppointments implements Appointments136 - database: ClinicDatabase137 + new(database: ClinicDatabase)138 + add(appointment: Appointment): void139 database.insert(appointment)140 return141142class AppointmentScheduler143 - appointments: Appointments144 + new(appointments: Appointments)145 + book(slot: Slot, patient: PatientId): void146 appointment := Appointment.book(slot, patient)147 appointments.add(appointment)148 return149150class ClinicApp151 + static start(database: ClinicDatabase): AppointmentScheduler152 return new AppointmentScheduler(153 new DatabaseAppointments(database))154```155156After, `AppointmentScheduler` holds the port and receives it through its157constructor. `DatabaseAppointments` adapts `ClinicDatabase` to that port,158and a call to `Appointments.add` is taken to store one appointment once.159`ClinicApp.start` is the composition root: it receives the open160database, builds the adapter once and the scheduler once, and is the161only place that names the adapter. The entry script opens the database162and passes it to `start`. `Appointment.book` is sent, not redeclared.163164## Red flags165166Places to look, not verdicts. A red flag becomes a finding only with167evidence: a measurement, a reproducible bug, or a failing test.168169- A domain class that imports a database, network, file or framework170 type.171- A constructor that creates its own collaborators with `new`.172- A static or global lookup for a collaborator inside a method.173- A test that needs a running database, a network or the real clock to174 check a domain rule.175- Object creation scattered across many classes instead of one root.176- A constructor that takes a locator or a container instead of the177 collaborators it uses.178179## Common mistakes180181- An interface for every class, including values and stable libraries182 with no side effects.183- A port that copies the outside library's methods, so the domain still184 speaks the library's terms.185- Passing the container itself into constructors, which is a service186 locator by another name.187- A composition root that also holds domain rules.188- Putting a framework's markers on domain classes so the framework can189 create them.190- Building the same object in two places, so the program has two graphs191 that drift apart.192193## Related skills194195- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule196 labels.197- [oo-encapsulating-what-varies](../oo-encapsulating-what-varies/SKILL.md)198 decides whether a seam has evidence.199- [oo-constructing-valid-objects](../oo-constructing-valid-objects/SKILL.md)200 keeps an object complete from its constructor, with every collaborator201 received.202- [oo-designing-interfaces](../oo-designing-interfaces/SKILL.md) shapes a203 port around the caller that sends it.204205## Further reading206207- [Ports and adapters](references/ports-and-adapters.md)208- [Composition roots](references/composition-roots.md)