Placing Domain Logic
In this pack:
sizing,
notation,
rule strictness.
Overview
A module's business rules can live in a few scripts, in objects that hold
their data, or in a service set beside them. The choice changes what a
second rule costs: a script grows another copy of a check, while an
object or a service has one place to change. This skill chooses the
style, keeps the use-case object to loading, delegating and storing, and
moves a rule that no single aggregate can decide to a domain service that
holds no state. The aim is one home for each rule, reachable from every
request that needs it.
When to use
- A controller or a use-case object holds a check on a status, a limit
or a date.
- Two entry points need the same check, and each has its own copy.
- A rule needs several aggregates, or an answer from outside, and no
single aggregate can decide it.
- A module mixes scripts that write fields with objects that keep their
own rules.
- A team is choosing between a transaction script, a domain model and a
table module for one module.
- A review asks whether a class is an application service, a domain
service or an entity method.
When not to use
- The question is which of two domain objects owns one behaviour, and no
service or layer is involved. That is
assigning responsibilities.
- The module has no business rule at all and only moves data between a
screen and a store, such as an admin form over a lookup table. Keep the
data path plain.
- The question is how a value checks its own format: that is
constructing valid objects.
Core rules
Judgement. Choose how a module organises its business logic by how
much its rules interact. A transaction script, one procedure per
request, suits a few independent rules, such as recording a patient's
preferred language. A domain model, objects that hold both data and
rules, suits rules that interact and grow, such as booking. A table
module, one class per table that acts on all its rows, suits tooling
built around sets of records. What tips the balance is whether the
same rule is needed by more than one request, and whether rules
depend on one another.
Rule. Keep an application service, the object one use case runs in,
to coordination: it loads aggregates through repositories, sends them
commands, stores them, opens and ends the transaction, and turns the
result into a reply. A business condition found in it moves into the
domain. This is the use-case object of
assigning responsibilities,
rule 5, with the loading, the storing and the transaction named.
Rule. Give an operation that no single aggregate can decide, because
it needs several aggregates or an answer from outside, to a domain
service: an object in the domain that keeps no state between calls,
named for the clinic activity it performs, such as VisitPricing,
that takes the aggregates and values it needs as parameters and
returns a decision or a value. It never loads or stores aggregates;
the application service does. Reach for it only after
assigning responsibilities,
rule 4, finds no domain object that can hold the rule. A domain
service that needs an answer from outside receives that port through
its constructor, as
inverting dependencies
rule 2 asks; one that needs none holds no field.
Default. Keep one style of business logic in one module: a module
with a domain model does not also grow transaction scripts that write
its objects' fields directly. The exception is a module moving from
scripts to a model one use case at a time. During the move each use
case is wholly in one style, and the scripts still to move are listed
where the team tracks the work.
Rule. Check that a request is well formed at the edge, and decide
whether it is allowed in the domain: the controller or the application
service turns text into values and refuses what cannot be read, such
as a date that does not parse, while whether this patient may book
this slot is decided by the domain objects. A value's own format is
checked once, by the value's constructor, as rule 3 of
constructing valid objects
asks; the edge only turns that failure into a reply.
Pattern
Before, the application service QuoteVisit holds two ports and decides
the price itself. It loads the rates for the clinician and the patient's
coverage, then chooses which amount to answer. After, VisitPricing
holds no field and makes that decision, and QuoteVisit only loads the
two values and delegates to it.
Before:
interface RateBook
+ ratesOf(clinician: ClinicianId): Rates
interface Covers
+ coverageOf(patient: PatientId): Coverage
class QuoteVisit
- rateBook: RateBook
- covers: Covers
+ new(rateBook: RateBook, covers: Covers)
+ run(kind: AppointmentKind, length: Duration,
clinician: ClinicianId, patient: PatientId): Fee
rates := rateBook.ratesOf(clinician)
coverage := covers.coverageOf(patient)
fee := rates.feeFor(kind, length)
if coverage.includes(kind) then
return coverage.patientShareOf(fee)
else
return fee
After:
interface RateBook
+ ratesOf(clinician: ClinicianId): Rates
interface Covers
+ coverageOf(patient: PatientId): Coverage
class QuoteVisit
- rateBook: RateBook
- covers: Covers
- pricing: VisitPricing
+ new(rateBook: RateBook, covers: Covers, pricing: VisitPricing)
+ run(kind: AppointmentKind, length: Duration,
clinician: ClinicianId, patient: PatientId): Fee
rates := rateBook.ratesOf(clinician)
coverage := covers.coverageOf(patient)
return pricing.quote(kind, length, rates, coverage)
class VisitPricing
+ quote(kind: AppointmentKind, length: Duration,
rates: Rates, coverage: Coverage): Fee
fee := rates.feeFor(kind, length)
if coverage.includes(kind) then
return coverage.patientShareOf(fee)
else
return fee
RateBook.ratesOf(clinician) is taken to answer the rates that apply to
that clinician, and Covers.coverageOf(patient) is taken to answer the
coverage that patient holds. They are the two ports, and an adapter at
the edge answers each. Coverage.includes(kind) is taken to mean that
the coverage covers that kind of appointment, and
Coverage.patientShareOf(fee) is taken to mean the part of that fee the
patient pays under the coverage.
Rates keeps the shape
limiting what an object knows
gives it, with feeFor(kind, length), and Coverage keeps the shape
diagnosing coupling gives it, with
its insurer, tier and lab-fee fields; both are used here as types.
AppointmentKind, Duration, ClinicianId, PatientId and Fee are
types only.
In both versions run sends rateBook.ratesOf once and
covers.coverageOf once; the after version also sends pricing.quote
once, and quote sends rates.feeFor once. The constructor sets every
field before run reads one, and no message runs twice. Neither fence
changes or stores an aggregate, so neither opens a transaction; a use
case that stores opens and ends one around its ports, as rule 2 asks.
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 business condition, such as a check on a status, a limit or a date,
in a controller or an application service.
- The same check copied into two use cases or two entry points.
- A domain service that loads or stores aggregates.
- A domain service that reads one aggregate's data and decides for it.
- A module where some use cases change objects through their methods and
others write the objects' fields directly.
Common mistakes
- Creating a service for each rule before asking which object holds its
data.
- Opening the transaction inside a domain object or a repository.
- Naming a service for a layer or a pattern rather than for the activity.
- Building a domain model for a module of a few independent rules.
- Checking business rules at the edge because the form already holds the
data.
Related skills
Further reading
- Three ways to organise
- Services by layer
1---2name: oo-placing-domain-logic3description: Use when choosing a domain service, entity method or application service, when use cases repeat one check, or picking scripts or a domain model.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-placing-domain-logic7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Placing Domain Logic1213**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 module's business rules can live in a few scripts, in objects that hold21their data, or in a service set beside them. The choice changes what a22second rule costs: a script grows another copy of a check, while an23object or a service has one place to change. This skill chooses the24style, keeps the use-case object to loading, delegating and storing, and25moves a rule that no single aggregate can decide to a domain service that26holds no state. The aim is one home for each rule, reachable from every27request that needs it.2829## When to use3031- A controller or a use-case object holds a check on a status, a limit32 or a date.33- Two entry points need the same check, and each has its own copy.34- A rule needs several aggregates, or an answer from outside, and no35 single aggregate can decide it.36- A module mixes scripts that write fields with objects that keep their37 own rules.38- A team is choosing between a transaction script, a domain model and a39 table module for one module.40- A review asks whether a class is an application service, a domain41 service or an entity method.4243## When not to use4445- The question is which of two domain objects owns one behaviour, and no46 service or layer is involved. That is47 [assigning responsibilities](../oo-assigning-responsibilities/SKILL.md).48- The module has no business rule at all and only moves data between a49 screen and a store, such as an admin form over a lookup table. Keep the50 data path plain.51- The question is how a value checks its own format: that is52 [constructing valid objects](../oo-constructing-valid-objects/SKILL.md).5354## Core rules55561. Judgement. **Choose how a module organises its business logic by how57 much its rules interact.** A transaction script, one procedure per58 request, suits a few independent rules, such as recording a patient's59 preferred language. A domain model, objects that hold both data and60 rules, suits rules that interact and grow, such as booking. A table61 module, one class per table that acts on all its rows, suits tooling62 built around sets of records. What tips the balance is whether the63 same rule is needed by more than one request, and whether rules64 depend on one another.65662. Rule. **Keep an application service, the object one use case runs in,67 to coordination: it loads aggregates through repositories, sends them68 commands, stores them, opens and ends the transaction, and turns the69 result into a reply. A business condition found in it moves into the70 domain.** This is the use-case object of71 [assigning responsibilities](../oo-assigning-responsibilities/SKILL.md),72 rule 5, with the loading, the storing and the transaction named.73743. Rule. **Give an operation that no single aggregate can decide, because75 it needs several aggregates or an answer from outside, to a domain76 service: an object in the domain that keeps no state between calls,77 named for the clinic activity it performs, such as `VisitPricing`,78 that takes the aggregates and values it needs as parameters and79 returns a decision or a value. It never loads or stores aggregates;80 the application service does.** Reach for it only after81 [assigning responsibilities](../oo-assigning-responsibilities/SKILL.md),82 rule 4, finds no domain object that can hold the rule. A domain83 service that needs an answer from outside receives that port through84 its constructor, as85 [inverting dependencies](../oo-inverting-dependencies/SKILL.md)86 rule 2 asks; one that needs none holds no field.87884. Default. **Keep one style of business logic in one module: a module89 with a domain model does not also grow transaction scripts that write90 its objects' fields directly.** The exception is a module moving from91 scripts to a model one use case at a time. During the move each use92 case is wholly in one style, and the scripts still to move are listed93 where the team tracks the work.94955. Rule. **Check that a request is well formed at the edge, and decide96 whether it is allowed in the domain: the controller or the application97 service turns text into values and refuses what cannot be read, such98 as a date that does not parse, while whether this patient may book99 this slot is decided by the domain objects.** A value's own format is100 checked once, by the value's constructor, as rule 3 of101 [constructing valid objects](../oo-constructing-valid-objects/SKILL.md)102 asks; the edge only turns that failure into a reply.103104## Pattern105106Before, the application service `QuoteVisit` holds two ports and decides107the price itself. It loads the rates for the clinician and the patient's108coverage, then chooses which amount to answer. After, `VisitPricing`109holds no field and makes that decision, and `QuoteVisit` only loads the110two values and delegates to it.111112Before:113114```text115interface RateBook116 + ratesOf(clinician: ClinicianId): Rates117118interface Covers119 + coverageOf(patient: PatientId): Coverage120121class QuoteVisit122 - rateBook: RateBook123 - covers: Covers124 + new(rateBook: RateBook, covers: Covers)125 + run(kind: AppointmentKind, length: Duration,126 clinician: ClinicianId, patient: PatientId): Fee127 rates := rateBook.ratesOf(clinician)128 coverage := covers.coverageOf(patient)129 fee := rates.feeFor(kind, length)130 if coverage.includes(kind) then131 return coverage.patientShareOf(fee)132 else133 return fee134```135136After:137138```text139interface RateBook140 + ratesOf(clinician: ClinicianId): Rates141142interface Covers143 + coverageOf(patient: PatientId): Coverage144145class QuoteVisit146 - rateBook: RateBook147 - covers: Covers148 - pricing: VisitPricing149 + new(rateBook: RateBook, covers: Covers, pricing: VisitPricing)150 + run(kind: AppointmentKind, length: Duration,151 clinician: ClinicianId, patient: PatientId): Fee152 rates := rateBook.ratesOf(clinician)153 coverage := covers.coverageOf(patient)154 return pricing.quote(kind, length, rates, coverage)155156class VisitPricing157 + quote(kind: AppointmentKind, length: Duration,158 rates: Rates, coverage: Coverage): Fee159 fee := rates.feeFor(kind, length)160 if coverage.includes(kind) then161 return coverage.patientShareOf(fee)162 else163 return fee164```165166`RateBook.ratesOf(clinician)` is taken to answer the rates that apply to167that clinician, and `Covers.coverageOf(patient)` is taken to answer the168coverage that patient holds. They are the two ports, and an adapter at169the edge answers each. `Coverage.includes(kind)` is taken to mean that170the coverage covers that kind of appointment, and171`Coverage.patientShareOf(fee)` is taken to mean the part of that fee the172patient pays under the coverage.173174`Rates` keeps the shape175[limiting what an object knows](../oo-limiting-what-an-object-knows/SKILL.md)176gives it, with `feeFor(kind, length)`, and `Coverage` keeps the shape177[diagnosing coupling](../oo-diagnosing-coupling/SKILL.md) gives it, with178its insurer, tier and lab-fee fields; both are used here as types.179`AppointmentKind`, `Duration`, `ClinicianId`, `PatientId` and `Fee` are180types only.181182In both versions `run` sends `rateBook.ratesOf` once and183`covers.coverageOf` once; the after version also sends `pricing.quote`184once, and `quote` sends `rates.feeFor` once. The constructor sets every185field before `run` reads one, and no message runs twice. Neither fence186changes or stores an aggregate, so neither opens a transaction; a use187case that stores opens and ends one around its ports, as rule 2 asks.188189## Red flags190191Places to look, not verdicts. A red flag becomes a finding only with192evidence: a measurement, a reproducible bug, or a failing test.193194- A business condition, such as a check on a status, a limit or a date,195 in a controller or an application service.196- The same check copied into two use cases or two entry points.197- A domain service that loads or stores aggregates.198- A domain service that reads one aggregate's data and decides for it.199- A module where some use cases change objects through their methods and200 others write the objects' fields directly.201202## Common mistakes203204- Creating a service for each rule before asking which object holds its205 data.206- Opening the transaction inside a domain object or a repository.207- Naming a service for a layer or a pattern rather than for the activity.208- Building a domain model for a module of a few independent rules.209- Checking business rules at the edge because the form already holds the210 data.211212## Related skills213214- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule215 labels.216- [oo-assigning-responsibilities](../oo-assigning-responsibilities/SKILL.md)217 chooses the use-case object and the domain object that owns a rule.218- [oo-designing-aggregates](../oo-designing-aggregates/SKILL.md) draws219 the boundary that one transaction keeps consistent.220- [oo-designing-repositories](../oo-designing-repositories/SKILL.md)221 gives the application service its ports and keeps a change whole.222- [oo-inverting-dependencies](../oo-inverting-dependencies/SKILL.md)223 puts each port and the composition root at the edge.224225## Further reading226227- [Three ways to organise](references/three-ways-to-organise.md)228- [Services by layer](references/services-by-layer.md)