Domain boundaries and maintainability
Prerequisite: node-architecture-decisions-and-modularity. Objective: Refactor fictional service contract. Each example is independent. Use Node.js 22.16.0 in a disposable directory; save as main.mjs and run node main.mjs. No external service is contacted.
How it works
For an order, the invariant might be that quantity is a positive integer and stock cannot become negative. Keep that invariant in a domain operation rather than duplicating it in each HTTP controller. A repository port describes what the operation needs, while an adapter implements actual persistence. Use transactions to enforce concurrent stock invariants in the real store. A fake adapter verifies logic but cannot prove database isolation or durability.
Enforce a domain invariant
function reserve(stock,qty){if(!Number.isInteger(qty)||qty<1||qty>stock)throw RangeError('quantity');return stock-qty;}console.log(reserve(5,2));try{reserve(5,6)}catch(e){console.log(e.message)}Expected output:
3quantityA valid reservation returns remaining stock; invalid quantity fails.
Inject a repository adapter
function getTitle(repo,id){return repo.get(id)?.title??null;}const repo={get:id=>id==='b1'?{title:'Node Basics'}:undefined};console.log(getTitle(repo,'b1'),getTitle(repo,'missing'));Expected output:
Node Basics nullA small explicit dependency permits tests without a database.
Common mistake
Do not introduce a generic repository for every object by default, or assume a pure domain test proves a concurrent database invariant.
Practice
Refactor a fictional controller that calculates stock twice into one domain function and a persistence adapter contract.
Reference candidate: node-domain-boundaries-and-maintainability-lookup (route unverified). Original instructional model; independent source review pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Domain boundaries and maintainability — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
Where should the quantity invariant be enforced?
What does a fake repository test establish?
Why use a port?