Layering the System
In this pack:
sizing,
notation,
rule strictness.
Overview
A layered system keeps its business rules at the centre and its outside
systems at the edge. The rule that produces the shape is simple: source
dependencies point inward, and an inner layer never names an outer one.
This skill draws that rule, gives each layer one job, keeps the hard
edges humble, sizes the number of layers to the ways in and out, and
lets a plain read skip the domain while every change goes through a use
case.
When to use
- You are choosing layered, hexagonal, onion or clean architecture.
- A domain or application class imports a web, screen or storage type.
- A screen, job or message listener needs its framework running before
a test can check it.
- A second way in, such as an import, copies a use case instead of
calling it.
- You are deciding how many layers a system with several ways in and
out needs.
- A read and a change both go through the domain, although the read
decides nothing.
When not to use
- The question is how one class gets its collaborators, such as a
constructor parameter or a port for a clock: that is
inverting dependencies.
- The question is which domain object, domain service or use case holds
a rule: that is
placing domain logic.
- The code is a script or a one-off tool with one way in and no
business rules to protect. Keep it a script.
- The question is how modules group by business area or depend on each
other. That is a question of module boundaries, not of the direction
between layers inside one module.
Core rules
Rule. Point every source dependency inward, toward the domain.
The domain depends on nothing outside itself. The application layer,
one object per use case, depends on the domain. The adapters for
screens, web requests, jobs, stores and outside services depend on
both, and the composition root depends on all of them. Where control
must flow outward, such as a use case storing an appointment, the
inner layer declares a port and an outer adapter implements it, as
inverting dependencies
rules 1 and 3 ask. Layered, hexagonal, onion and clean architectures
are drawings of this one rule.
Rule. Keep each layer to its job. The domain holds the business
rules. The application layer loads, delegates, stores and sets the
transaction, as
placing domain logic rule 2
asks. An adapter turns outside input into a call on a use case and
the reply into outside output. A business condition found in an
adapter moves inward, as
assigning responsibilities
rule 5 asks of an interface.
Rule. Cross an inner boundary only with the inner layer's types.
An adapter turns the framework's request into the values a use case
takes, and the use case answers with its own values or raises its own
errors. No framework request, storage row or framework marker reaches
the application or the domain. A request that arrives as a transfer
object is converted once at the edge, as
deciding object or data
rule 3 asks.
Default. Make each edge that is hard to test a humble object. A
screen, a scheduled job or a message listener keeps only the code
that needs its framework, such as reading the input and writing the
output, and sends everything else to an object that can be tested
without the framework.
The exception is an edge with nothing to decide, such as a health
check that always gives the same answer: it needs no split.
Judgement. Choose how many layers by how many ways in and out the
system has. A small service with one entry point and one store may
keep its use cases and adapters close around the domain, while a
system booked from a web page, a nightly import and another team's
service earns the full set, so every entry point calls the same use
cases. What tips the balance is the number of entry points and
outside systems, and whether the business rules must be tested
without them.
Judgement. Let a read that applies no business rule skip the domain
and go through a read query that returns plain data. Today's
appointments listed for a screen are such a read, while every change
goes through a use case and the domain. What tips the balance is
whether the read decides anything: a read that decides who may see
what is a use case. The read query is
designing repositories
rule 6.
Pattern
FrameworkController, FrameworkRequest, FrameworkReply and the
reference's FrameworkJob and JobRun stand for any framework's own
types; this skill names no framework.
Before, WaitingListController owns the use case. It reads the request,
loads the list, joins the patient and saves the list, so the use case
lives in a class that needs the web framework and the database to run,
and a nightly import that also adds patients to waiting lists cannot
reach it.
Before:
-- adapters
class WaitingListController extends FrameworkController
- database: ClinicDatabase
+ new(database: ClinicDatabase)
+ post(request: FrameworkRequest): FrameworkReply
clinician := clinicianIn(request)
list := database.waitingListFor(clinician)
list.join(patientIn(request))
database.saveWaitingList(clinician, list)
return FrameworkReply.ok()
- clinicianIn(request: FrameworkRequest): ClinicianId
- patientIn(request: FrameworkRequest): PatientId
After, the domain holds the list and its rule, the application layer
holds JoinWaitingList, and the adapters translate the request and the
store. clinicianIn and patientIn read the form's text into the
values and refuse text that cannot be read. waitingListFor is taken to
answer the waiting list stored under a clinician, and saveWaitingList
is taken to store it there once. WaitingLists.save takes the clinician
because a WaitingList holds no identity of its own. The clinic keeps
one waiting list per clinician, so the list is stored under its
clinician's identity, in the clinic's database, in the transaction run
opens. AlreadyWaiting from join passes on to the framework, which
turns it into a reply. FrameworkReply.ok() is taken to answer a reply
that reports success. The controller still extends the framework's
controller base class, because the framework calls post; the business
step now sits in the application layer. Both versions send join once
and store the list once: the before version through
database.saveWaitingList, the after version through waitingLists.save.
Every field type in the after version belongs to its own layer or an
inner one: WaitingLists and WaitingList are domain types,
JoinWaitingList is an application type, and ClinicDatabase is the
type the inverting skill gives the store, held only by the adapter.
After:
-- domain
class WaitingList
- patients: List<PatientId>
+ new()
patients := new List<PatientId>()
+ join(patient: PatientId): void
raises AlreadyWaiting
if patients.contains(patient) then
raise AlreadyWaiting
else
patients.add(patient)
return
+ waiting(): ReadOnlyList<PatientId>
return patients.readOnlyView()
interface WaitingLists
+ forClinician(clinician: ClinicianId): WaitingList
+ save(clinician: ClinicianId, list: WaitingList): void
-- application
class JoinWaitingList
- waitingLists: WaitingLists
+ new(waitingLists: WaitingLists)
+ run(clinician: ClinicianId, patient: PatientId): void
list := waitingLists.forClinician(clinician)
list.join(patient)
waitingLists.save(clinician, list)
return
-- adapters
class WaitingListController extends FrameworkController
- joinWaitingList: JoinWaitingList
+ new(joinWaitingList: JoinWaitingList)
+ post(request: FrameworkRequest): FrameworkReply
joinWaitingList.run(clinicianIn(request), patientIn(request))
return FrameworkReply.ok()
- clinicianIn(request: FrameworkRequest): ClinicianId
- patientIn(request: FrameworkRequest): PatientId
class DatabaseWaitingLists implements WaitingLists
- database: ClinicDatabase
+ new(database: ClinicDatabase)
+ forClinician(clinician: ClinicianId): WaitingList
return database.waitingListFor(clinician)
+ save(clinician: ClinicianId, list: WaitingList): void
database.saveWaitingList(clinician, list)
return
WaitingList keeps the shape the composition skill gives it. The
-- domain, -- application and -- adapters comments mark the three
layers. DatabaseWaitingLists.forClinician sends waitingListFor once
and save sends saveWaitingList once.
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 or application class that imports a web, user-interface or
storage framework type.
- A domain class that extends a framework's base class or carries its
markers.
- A second way in, such as an import or a job, that reaches a use case
by faking a web request.
- Tests of business rules that start a server or a database.
- A use case that takes or returns a framework's request, response or
row type.
- A store's interface declared beside its database adapter rather than
beside the domain.
Common mistakes
- Adding a layer for each technical kind, such as controllers, services,
managers and helpers, each calling the next whatever the change.
- Routing every read through the domain model even when no rule applies.
- Treating hexagonal, onion and clean as rival designs to choose
between rather than one rule drawn three ways.
- Putting decisions in the composition root or in framework
configuration.
- Testing a humble edge in depth while the object it calls goes
untested.
Related skills
Further reading
- One rule, four drawings
- Humble edges
1---2name: oo-layering-the-system3description: Use when choosing layered, hexagonal or clean architecture, when an inner layer imports an outer one, or a screen needs its framework in tests.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-layering-the-system7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Layering the System1213**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## Overview1920A layered system keeps its business rules at the centre and its outside21systems at the edge. The rule that produces the shape is simple: source22dependencies point inward, and an inner layer never names an outer one.23This skill draws that rule, gives each layer one job, keeps the hard24edges humble, sizes the number of layers to the ways in and out, and25lets a plain read skip the domain while every change goes through a use26case.2728## When to use2930- You are choosing layered, hexagonal, onion or clean architecture.31- A domain or application class imports a web, screen or storage type.32- A screen, job or message listener needs its framework running before33 a test can check it.34- A second way in, such as an import, copies a use case instead of35 calling it.36- You are deciding how many layers a system with several ways in and37 out needs.38- A read and a change both go through the domain, although the read39 decides nothing.4041## When not to use4243- The question is how one class gets its collaborators, such as a44 constructor parameter or a port for a clock: that is45 [inverting dependencies](../oo-inverting-dependencies/SKILL.md).46- The question is which domain object, domain service or use case holds47 a rule: that is48 [placing domain logic](../oo-placing-domain-logic/SKILL.md).49- The code is a script or a one-off tool with one way in and no50 business rules to protect. Keep it a script.51- The question is how modules group by business area or depend on each52 other. That is a question of module boundaries, not of the direction53 between layers inside one module.5455## Core rules56571. Rule. **Point every source dependency inward, toward the domain.**58 The domain depends on nothing outside itself. The application layer,59 one object per use case, depends on the domain. The adapters for60 screens, web requests, jobs, stores and outside services depend on61 both, and the composition root depends on all of them. Where control62 must flow outward, such as a use case storing an appointment, the63 inner layer declares a port and an outer adapter implements it, as64 [inverting dependencies](../oo-inverting-dependencies/SKILL.md)65 rules 1 and 3 ask. Layered, hexagonal, onion and clean architectures66 are drawings of this one rule.67682. Rule. **Keep each layer to its job.** The domain holds the business69 rules. The application layer loads, delegates, stores and sets the70 transaction, as71 [placing domain logic](../oo-placing-domain-logic/SKILL.md) rule 272 asks. An adapter turns outside input into a call on a use case and73 the reply into outside output. A business condition found in an74 adapter moves inward, as75 [assigning responsibilities](../oo-assigning-responsibilities/SKILL.md)76 rule 5 asks of an interface.77783. Rule. **Cross an inner boundary only with the inner layer's types.**79 An adapter turns the framework's request into the values a use case80 takes, and the use case answers with its own values or raises its own81 errors. No framework request, storage row or framework marker reaches82 the application or the domain. A request that arrives as a transfer83 object is converted once at the edge, as84 [deciding object or data](../oo-deciding-object-or-data/SKILL.md)85 rule 3 asks.86874. Default. **Make each edge that is hard to test a humble object.** A88 screen, a scheduled job or a message listener keeps only the code89 that needs its framework, such as reading the input and writing the90 output, and sends everything else to an object that can be tested91 without the framework.9293 The exception is an edge with nothing to decide, such as a health94 check that always gives the same answer: it needs no split.95965. Judgement. **Choose how many layers by how many ways in and out the97 system has.** A small service with one entry point and one store may98 keep its use cases and adapters close around the domain, while a99 system booked from a web page, a nightly import and another team's100 service earns the full set, so every entry point calls the same use101 cases. What tips the balance is the number of entry points and102 outside systems, and whether the business rules must be tested103 without them.1041056. Judgement. **Let a read that applies no business rule skip the domain106 and go through a read query that returns plain data.** Today's107 appointments listed for a screen are such a read, while every change108 goes through a use case and the domain. What tips the balance is109 whether the read decides anything: a read that decides who may see110 what is a use case. The read query is111 [designing repositories](../oo-designing-repositories/SKILL.md)112 rule 6.113114## Pattern115116`FrameworkController`, `FrameworkRequest`, `FrameworkReply` and the117reference's `FrameworkJob` and `JobRun` stand for any framework's own118types; this skill names no framework.119120Before, `WaitingListController` owns the use case. It reads the request,121loads the list, joins the patient and saves the list, so the use case122lives in a class that needs the web framework and the database to run,123and a nightly import that also adds patients to waiting lists cannot124reach it.125126Before:127128```text129-- adapters130class WaitingListController extends FrameworkController131 - database: ClinicDatabase132 + new(database: ClinicDatabase)133 + post(request: FrameworkRequest): FrameworkReply134 clinician := clinicianIn(request)135 list := database.waitingListFor(clinician)136 list.join(patientIn(request))137 database.saveWaitingList(clinician, list)138 return FrameworkReply.ok()139 - clinicianIn(request: FrameworkRequest): ClinicianId140 - patientIn(request: FrameworkRequest): PatientId141```142143After, the domain holds the list and its rule, the application layer144holds `JoinWaitingList`, and the adapters translate the request and the145store. `clinicianIn` and `patientIn` read the form's text into the146values and refuse text that cannot be read. `waitingListFor` is taken to147answer the waiting list stored under a clinician, and `saveWaitingList`148is taken to store it there once. `WaitingLists.save` takes the clinician149because a `WaitingList` holds no identity of its own. The clinic keeps150one waiting list per clinician, so the list is stored under its151clinician's identity, in the clinic's database, in the transaction `run`152opens. `AlreadyWaiting` from `join` passes on to the framework, which153turns it into a reply. `FrameworkReply.ok()` is taken to answer a reply154that reports success. The controller still extends the framework's155controller base class, because the framework calls `post`; the business156step now sits in the application layer. Both versions send `join` once157and store the list once: the before version through158`database.saveWaitingList`, the after version through `waitingLists.save`.159Every field type in the after version belongs to its own layer or an160inner one: `WaitingLists` and `WaitingList` are domain types,161`JoinWaitingList` is an application type, and `ClinicDatabase` is the162type the inverting skill gives the store, held only by the adapter.163164After:165166```text167-- domain168class WaitingList169 - patients: List<PatientId>170 + new()171 patients := new List<PatientId>()172 + join(patient: PatientId): void173 raises AlreadyWaiting174 if patients.contains(patient) then175 raise AlreadyWaiting176 else177 patients.add(patient)178 return179 + waiting(): ReadOnlyList<PatientId>180 return patients.readOnlyView()181182interface WaitingLists183 + forClinician(clinician: ClinicianId): WaitingList184 + save(clinician: ClinicianId, list: WaitingList): void185186-- application187class JoinWaitingList188 - waitingLists: WaitingLists189 + new(waitingLists: WaitingLists)190 + run(clinician: ClinicianId, patient: PatientId): void191 list := waitingLists.forClinician(clinician)192 list.join(patient)193 waitingLists.save(clinician, list)194 return195196-- adapters197class WaitingListController extends FrameworkController198 - joinWaitingList: JoinWaitingList199 + new(joinWaitingList: JoinWaitingList)200 + post(request: FrameworkRequest): FrameworkReply201 joinWaitingList.run(clinicianIn(request), patientIn(request))202 return FrameworkReply.ok()203 - clinicianIn(request: FrameworkRequest): ClinicianId204 - patientIn(request: FrameworkRequest): PatientId205206class DatabaseWaitingLists implements WaitingLists207 - database: ClinicDatabase208 + new(database: ClinicDatabase)209 + forClinician(clinician: ClinicianId): WaitingList210 return database.waitingListFor(clinician)211 + save(clinician: ClinicianId, list: WaitingList): void212 database.saveWaitingList(clinician, list)213 return214```215216`WaitingList` keeps the shape the composition skill gives it. The217`-- domain`, `-- application` and `-- adapters` comments mark the three218layers. `DatabaseWaitingLists.forClinician` sends `waitingListFor` once219and `save` sends `saveWaitingList` once.220221## Red flags222223Places to look, not verdicts. A red flag becomes a finding only with224evidence: a measurement, a reproducible bug, or a failing test.225226- A domain or application class that imports a web, user-interface or227 storage framework type.228- A domain class that extends a framework's base class or carries its229 markers.230- A second way in, such as an import or a job, that reaches a use case231 by faking a web request.232- Tests of business rules that start a server or a database.233- A use case that takes or returns a framework's request, response or234 row type.235- A store's interface declared beside its database adapter rather than236 beside the domain.237238## Common mistakes239240- Adding a layer for each technical kind, such as controllers, services,241 managers and helpers, each calling the next whatever the change.242- Routing every read through the domain model even when no rule applies.243- Treating hexagonal, onion and clean as rival designs to choose244 between rather than one rule drawn three ways.245- Putting decisions in the composition root or in framework246 configuration.247- Testing a humble edge in depth while the object it calls goes248 untested.249250## Related skills251252- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule253 labels.254- [oo-inverting-dependencies](../oo-inverting-dependencies/SKILL.md)255 puts a port beside the domain, an adapter at the edge and the256 composition root at the program's start.257- [oo-placing-domain-logic](../oo-placing-domain-logic/SKILL.md) keeps258 the use-case object to loading, delegating, storing and the259 transaction.260- [oo-assigning-responsibilities](../oo-assigning-responsibilities/SKILL.md)261 chooses the use-case object and the domain object that owns a rule.262- [oo-designing-repositories](../oo-designing-repositories/SKILL.md)263 gives the application layer its ports and its read queries.264- [oo-separating-presentation-from-domain](../oo-separating-presentation-from-domain/SKILL.md)265 keeps a screen humble with a presentation object.266267## Further reading268269- [One rule, four drawings](references/one-rule-four-drawings.md)270- [Humble edges](references/humble-edges.md)