OBEY Domain-Driven Design by Eric Evans
Purpose
This repository follows Domain-Driven Design.
All code generation, modification, and review must optimize for:
- a precise model of the domain
- a shared ubiquitous language
- explicit bounded contexts
- rich domain behavior where complexity exists
- disciplined aggregate design
- protection of invariants
- clear separation between domain model and supporting infrastructure
This file is a binding engineering policy: MUST is binding, SHOULD is a strong default, and MUST NOT is forbidden.
Primary Directive
When uncertain, prefer the option that makes the domain model clearer.
Do not optimize primarily for:
- fewer files
- generic reuse
- CRUD convenience
- object-relational mapping convenience
- delivery-layer convenience
- framework conventions
- short-term speed at the cost of model clarity
The model must serve the business meaning first.
What DDD Means in This Repository
DDD here does not mean:
- adding layers for ceremony
- renaming service classes to sound sophisticated
- wrapping CRUD in verbose abstractions
- creating entities with only fields and setters
- turning every concept into an aggregate
- introducing every DDD pattern everywhere
- overengineering simple subdomains
DDD here does mean:
- building code around business concepts
- expressing rules in domain language
- making context boundaries explicit
- protecting invariants with the model
- modeling identity, value, lifecycle, and consistency deliberately
- translating explicitly across context boundaries
- simplifying aggressively outside the core domain
Knowledge Crunching and Deep Models
Rules (MUST unless marked SHOULD or MUST NOT)
- Treat the model as discovered, not invented from technical structure.
- Before adding abstractions, identify what domain experts would call the concept.
- When requirements are ambiguous, look for missing domain distinctions instead of forcing generic names.
- Let awkward code, contradictory language, and repeated conditionals trigger deeper modeling.
- Update names and boundaries when new domain insight appears.
Required behavior (MUST)
- Ask what business rule, policy, lifecycle, or invariant the code is expressing.
- Prefer a deeper model that clarifies behavior over a shallow model that merely stores data.
- Capture newly discovered concepts in names, tests, APIs, and modules.
- Treat refactoring as part of model discovery, not just code cleanup.
Anti-patterns (MUST NOT)
- Starting from database tables and calling the result the domain model
- Preserving vague names after discovering sharper domain language
- Hiding domain complexity behind
type, status, or metadata fields
- Treating the first model as final
Model-Driven Design
Rules (MUST unless marked SHOULD or MUST NOT)
- The implemented design must reflect the model used in discussion.
- If the model cannot guide code, refine the model or the code until they align.
- Domain objects must represent behavior and meaning, not just persistence state.
- Keep modelers close to implementation. Do not separate analysis from coding so far that the model becomes theoretical.
Required behavior (MUST)
- Make important model concepts visible in classes, functions, modules, tests, and interfaces.
- Prefer executable examples and tests over disconnected documentation.
- Keep diagrams and documents lightweight, current, and tied to code.
- Use explanatory models only to teach or reason; do not confuse them with the implementation model unless they are intended to drive code.
Anti-patterns (MUST NOT)
- A design document that uses different names than the code
- Analysts producing models that developers cannot or do not implement
- Code that follows framework conventions while ignoring the domain model
- Diagrams that become authoritative after the code and domain understanding have changed
Breakthrough and Deeper Insight
Rules (MUST unless marked SHOULD or MUST NOT)
- Expect useful models to change after deeper insight.
- Treat a breakthrough model as a candidate for deliberate refactoring, not as churn.
- When a better model appears, compare its explanatory power against migration cost.
- Preserve working behavior while moving toward the deeper model in safe steps.
Required behavior (MUST)
- Look for concepts that simplify many special cases at once.
- Prefer changes that make future business rules easier to express.
- Use awkwardness, contradictions, and repeated failed attempts as signals that the model is shallow.
- Keep focus on the basics when the model becomes too elaborate.
Anti-patterns (MUST NOT)
- Rejecting a better model only because the current one already works
- Big-bang rewrites when incremental migration is possible
- Elaborate abstractions that do not improve domain insight
Making Implicit Concepts Explicit
Rules (MUST unless marked SHOULD or MUST NOT)
- Listen for domain language that is not represented in code.
- Scrutinize awkward APIs, repeated branches, and contradictory names.
- Read domain references, policies, regulations, and prior art when available.
- Try multiple model shapes before settling on one for complex concepts.
Required behavior (MUST)
- Promote hidden constraints, policies, and processes into explicit domain concepts.
- Name the concept before choosing the implementation form.
- Prefer clear domain objects over anonymous helpers when behavior has business meaning.
Anti-patterns (MUST NOT)
- Burying business rules in comments
- Treating contradictions as edge cases instead of modeling signals
- Keeping vague technical flags after discovering the real concept
Ubiquitous Language
Rules (MUST unless marked SHOULD or MUST NOT)
- Use the exact business terms used by domain experts inside a bounded context.
- One concept must have one name inside a bounded context.
- One name must not mean different concepts inside a bounded context.
- Method names, test names, and modules must use the same vocabulary as the domain.
- Rename code when the domain understanding improves.
Required behavior (MUST)
- Prefer names from the active bounded context; in a shipping model, terms such as
Cargo, Itinerary, Handling Event, and Route Specification should appear directly.
- Prefer operation names that express the domain action, such as changing a cargo destination, adding a handling event, checking allocation, or applying an overbooking policy.
- Avoid technical placeholders when a precise domain term exists.
- Avoid names imported from another bounded context without translation.
Anti-patterns (MUST NOT)
- Using technical names where the business has precise names
- Using synonyms for the same concept in the same context
- Reusing the same term for different meanings because it is convenient
- Keeping bad names because they already exist in the database
Communication Artifacts
Rules (MUST unless marked SHOULD or MUST NOT)
- Documents and diagrams must support the ubiquitous language.
- Written design material must be short enough to stay maintained.
- Executable tests are preferred for rules that can be verified.
- Diagrams should emphasize boundaries, relationships, invariants, and lifecycle over class inventory.
Required behavior (MUST)
- Use examples and scenario tests as living documentation.
- Keep glossary-like explanations close to the bounded context they describe.
- Update documents when terminology or context boundaries change.
Anti-patterns (MUST NOT)
- Long design documents that drift away from code
- Diagrams that show every class but hide the model's meaning
- Documentation that introduces vocabulary not used by code or tests
Scenario Walkthroughs
Rules (MUST unless marked SHOULD or MUST NOT)
- Validate the model by walking through real application scenarios.
- Use scenarios to test whether entities, value objects, aggregates, repositories, and factories collaborate naturally.
- When a scenario feels procedural or awkward, look for missing model concepts or wrong boundaries.
- Revisit aggregate and module boundaries after scenario walkthroughs reveal pressure.
Required behavior (MUST)
- Prefer examples that exercise real business decisions, not only CRUD paths.
- Use scenarios to verify object creation, lifecycle transitions, and cross-context translation.
- Let performance tuning follow model clarity; do not distort the model prematurely for optimization.
Anti-patterns (MUST NOT)
- Designing model elements only in isolation
- Treating scenario code as an afterthought after infrastructure is complete
- Optimizing persistence paths before the model expresses the business correctly
Layered Architecture and Smart UI
Rules (MUST unless marked SHOULD or MUST NOT)
- Keep the domain layer as the place where the model and business rules live.
- Separate presentation, application coordination, domain behavior, and infrastructure when the domain is complex enough to need model-driven design.
- Let application code coordinate tasks without owning domain decisions.
- Keep infrastructure services and framework concerns outside domain objects.
- Use Smart UI only for simple applications where rich domain abstraction, reuse, integration, and deep business rules are not important.
Anti-patterns (MUST NOT)
- UI screens, database tables, or framework annotations defining the domain vocabulary
- UI, application coordination, jobs, or scripts carrying domain rules while domain objects stay passive
- choosing Smart UI when the business behavior needs reuse or abstraction
Bounded Contexts
Rules (MUST unless marked SHOULD or MUST NOT)
- Every substantial domain area must belong to a clearly identified bounded context.
- A model is valid only inside its own bounded context.
- Concepts from another context must not be imported directly as if they were native.
- Translation across contexts must be explicit.
- Shared models across multiple contexts are forbidden unless intentionally governed as a shared kernel.
Required behavior (MUST)
- Keep package, module, or namespace ownership explicit.
- Model
Customer separately in different contexts if meanings differ.
- Prefer context-specific contracts, IDs, published language, or anticorruption layers over shared classes.
Anti-patterns (MUST NOT)
- One giant company-wide domain model
- A
shared/domain package that erases boundaries
- Copying foreign terms into the local model without translation
- Reusing one aggregate type across unrelated contexts
Strategic Design
Core Domain
- Invest the most care in the core domain.
- Protect the core domain from foreign models, vendor schemas, and generic abstractions.
- Keep the core domain expressive even if supporting areas are simpler.
Supporting and Generic Subdomains
- Do not over-model commodity concerns.
- Use simpler models where business complexity is low.
- Save the richest modeling effort for the parts that matter strategically.
Context Mapping
- Integration relationships must be visible in code.
- Ownership of translation must be explicit.
- Upstream and downstream influence must be reflected in adapters and contracts.
Anti-patterns (MUST NOT)
- Spending more design effort on plumbing than on the core domain
- Modeling authentication utilities more richly than the pricing engine
- Allowing a legacy system vocabulary to dominate the core model
Model Integrity Patterns
Continuous Integration Within a Context
- A bounded context must keep one internally consistent model.
- Team members working in the same context must integrate terminology and model changes continuously.
- Conflicting meanings inside one context must be resolved quickly through naming, tests, and refactoring.
Context Relationships
Use context relationship patterns intentionally:
Shared Kernel only for a small, jointly governed model subset.
Customer/Supplier when an upstream team commits to downstream needs.
Conformist only when adopting the upstream model is cheaper than translating it.
Anticorruption Layer when protecting the local model from a foreign or legacy model.
Separate Ways when integration cost is higher than shared capability value.
Open Host Service when a context exposes a stable integration protocol.
Published Language when contexts need a documented exchange language.
Context Transformations
- Move from Separate Ways to Shared Kernel only when the overlap is small, valuable, and worth coordination.
- Move from Shared Kernel to Continuous Integration only when teams are ready to share one model frequently.
- Phase out legacy systems by protecting the new model and replacing responsibilities incrementally through translations.
- Evolve Open Host Service toward Published Language when interchange stability is needed beyond one service.
Required behavior (MUST)
- Make context maps visible in package structure, integration adapters, documentation, or tests.
- Name adapters after the relationship they implement when that improves clarity.
- Keep foreign model terms out of the local core unless deliberately accepted as conformist.
Anti-patterns (MUST NOT)
- Accidental shared kernels with no ownership rules
- Calling every integration an anticorruption layer without translation
- Letting upstream APIs silently define downstream domain language
- Treating context mapping as architecture documentation only, not code structure
Distillation
Core Domain
- Identify the part of the model that creates strategic advantage.
- Put the strongest modeling effort and cleanest design into that core.
- Do not bury the core under generic mechanisms, infrastructure, or broad shared abstractions.
Distillation Patterns
Use these patterns when they clarify priority and investment:
Domain Vision Statement for a short statement of the core model's purpose.
Highlighted Core to mark the most important elements inside a larger model.
Generic Subdomain for commodity capabilities that do not deserve rich custom modeling.
Cohesive Mechanism for technical mechanisms that can be separated from domain policy.
Segregated Core when the core is tangled with supporting concerns.
Abstract Core when related specialized models need a stable conceptual foundation.
Required behavior (MUST)
- Make the core domain easy to find in code.
- Keep supporting and generic subdomains simpler unless their complexity is real.
- Choose refactoring targets based on strategic importance, not just local messiness.
Anti-patterns (MUST NOT)
- Spending equal modeling effort on every subsystem
- Letting technical mechanisms dominate the core model
- Hiding the core behind generic shared packages
- Refactoring peripheral code while the core remains unclear
Large-Scale Structure
Rules (MUST unless marked SHOULD or MUST NOT)
- Large-scale structure should help people understand the system, not freeze it.
- Let structure evolve as the model evolves.
- Use a guiding structure only when it reduces cognitive load across contexts.
- Keep the structure minimally restrictive.
Patterns
Use these patterns deliberately:
Evolving Order when structure must emerge through iterative modeling.
System Metaphor only when it genuinely clarifies the model.
Responsibility Layers when responsibilities naturally stratify across the system.
Knowledge Level when rules or policies must be represented explicitly and changed by configuration or data.
Pluggable Component Framework when variation points are stable and worth formalizing.
Required behavior (MUST)
- Combine bounded contexts, distillation, and large-scale structure into one coherent strategy.
- Revisit structure when it no longer fits the model.
- Prefer communication and self-discipline over heavy structural machinery where possible.
Anti-patterns (MUST NOT)
- A master plan that blocks model learning
- A metaphor that sounds clever but misleads design decisions
- Overly restrictive layers that fight the domain
- Framework architecture masquerading as domain structure
Strategic Decision Making
Rules (MUST unless marked SHOULD or MUST NOT)
- Assess the current model and context map before prescribing a strategic structure.
- Decide who owns strategic design choices explicitly.
- Let application development inform strategy; do not impose strategy detached from implementation feedback.
- Architecture teams must stay customer-focused and model-focused, not framework-focused.
- Strategic decisions must remain revisable as domain understanding changes.
Required behavior (MUST)
- Combine bounded contexts with distillation and large-scale structure when system complexity requires it.
- Make strategy visible enough that teams can coordinate without a rigid master plan.
- Keep technical frameworks subordinate to the domain strategy.
- Treat strategic design as team decision-making, not just diagram production.
Anti-patterns (MUST NOT)
- A top-down master plan that ignores model learning
- Strategy owned by people disconnected from implementation
- Technical architecture decisions presented as domain strategy
- Context maps, core-domain decisions, and large-scale structures that are never revisited
Entities
Use entities when
- identity matters over time
- lifecycle matters
- continuity matters beyond current attributes
- business rules depend on “which one” rather than only “what value”
Rules (MUST unless marked SHOULD or MUST NOT)
- Entities must have explicit identity.
- Entities must protect their own valid state transitions.
- Entities must expose intention-revealing behavior, not arbitrary state changes.
- Entities must not be treated as passive records in behavior-rich domains.
Required behavior (MUST)
- Prefer methods that tell an entity what domain action to perform.
- In a shipping model, express destination changes and handling-event additions as model operations rather than procedural data edits.
- Hide direct state changes behind methods that encode domain meaning.
- Keep identity stable and explicit.
Anti-patterns (MUST NOT)
- Public setters for every field
- Application services manually editing all entity state
- UI or application code deciding which transitions are valid
- Entities used only as persistence shells
Value Objects
Use value objects when
- a concept is defined by attributes rather than identity
- the concept has validation rules
- the concept has behavior
- passing a primitive would hide meaning
Rules (MUST unless marked SHOULD or MUST NOT)
- Value objects must be immutable by default.
- Construction must guarantee validity.
- Equality must be by value, not by identity.
- Validation for the concept should live inside the value object.
- Replace primitive obsession aggressively where the concept matters.
Required behavior (MUST)
- Use value objects for descriptive concepts whose attributes together carry domain meaning.
- Name value objects after the domain concept, not the primitive representation.
- Keep validation and side-effect-free operations for the value near the value itself.
- Replace raw primitives when a named quantity, range, code, measurement, or descriptive whole value matters to the model.
Anti-patterns (MUST NOT)
- Repeating the same value validation across handlers
- Passing raw primitives for named domain quantities, ranges, codes, or measurements
- Passing raw strings for meaningful identifiers
- Letting invalid values exist temporarily without an explicit model for incompleteness
Associations and Modules
Associations
- Model associations only when they support behavior or meaning.
- Prefer simpler, more navigable associations over fully connected object graphs.
- Reduce bidirectional associations unless the domain requires them.
- Reference other aggregates by identity unless direct object traversal is part of an invariant boundary.
Modules
- Modules must communicate domain concepts and bounded context ownership.
- Organize modules around model meaning, not only technical layers.
- Keep related concepts together when they change together.
- Avoid infrastructure-driven packaging that hides the domain.
Required behavior (MUST)
- Use package names that match the ubiquitous language.
- Keep model concepts discoverable from the directory structure.
- Split modules when different concepts evolve independently.
Anti-patterns (MUST NOT)
models, services, utils, and helpers as the dominant structure
- Associations created only because the persistence mechanism supports them
- Object graphs that make aggregate boundaries invisible
- Modules grouped by technical artifact while domain concepts are scattered
Aggregates
Purpose
Aggregates are consistency boundaries, not just object graphs.
Rules (MUST unless marked SHOULD or MUST NOT)
- Design aggregates around invariants that must be consistent immediately.
- Keep aggregates as small as possible.
- All modifications that affect aggregate invariants must go through the aggregate root.
- Reference other aggregates by identity unless stronger consistency is truly required.
- Keep transactional boundaries aligned with invariants; do not expand transactions across aggregates merely for convenience.
Required behavior (MUST)
- Put invariant-protecting methods on the aggregate root.
- Keep internal members encapsulated.
- Handle consistency across aggregate boundaries deliberately when the invariant does not belong inside one aggregate.
- Model transactional boundaries deliberately.
Anti-patterns (MUST NOT)
- Large graph aggregates built for object-relational mapping convenience
- Aggregate roots exposing internal collections for arbitrary external state changes
- Transactions modifying many aggregates because object references make it easy
- Confusing parent-child object structure with aggregate boundaries
Domain Services
Use a domain service only when
- the behavior is domain-significant
- the behavior does not naturally belong on one entity or value object
- the operation still belongs to the ubiquitous language
Rules (MUST unless marked SHOULD or MUST NOT)
- A domain service must express a domain concept, not a technical convenience.
- If behavior clearly belongs to an entity or value object, keep it there.
- Do not move behavior into services merely to keep entities thin.
Required behavior (MUST)
- Domain services should sound like the business.
- Domain services should coordinate domain concepts, not infrastructure details.
Anti-patterns (MUST NOT)
- a single
*Service containing all rules for a model area
- a service containing dozens of unrelated policies
- “Domain services” that are only wrappers for repositories or external technical clients
- Extracting behavior from entities prematurely
Explicit Concepts and Specifications
Rules (MUST unless marked SHOULD or MUST NOT)
- Make implicit constraints explicit in the model.
- Model domain processes as domain objects when the process has business meaning.
- Use specifications for named, combinable business rules that answer whether something satisfies a criterion.
- Keep specifications in domain language, not query language.
Required behavior (MUST)
- Extract repeated conditionals into named domain concepts.
- Prefer named concepts such as route specifications, overbooking policies, or allocation rules over anonymous boolean expressions.
- Keep persistence querying concerns separate from domain specifications unless the project deliberately provides translation.
- Use specifications to clarify policy, validation, selection, and compatibility rules.
Anti-patterns (MUST NOT)
- Complex business conditions duplicated across services
- Boolean flags that hide a named domain rule
- Specifications that are just persistence query builders
- Processes represented only as scripts or transaction handlers when the business treats them as concepts
Repositories
Purpose
Repositories provide access to aggregates as part of the model.
Rules (MUST unless marked SHOULD or MUST NOT)
- Repositories exist for aggregate roots, not for every table.
- Repository interfaces must be defined by the domain or application model that uses them.
- Repositories must return domain objects or domain-oriented results.
- Repository contracts must reflect intent where useful.
- Repositories must not become universal query utilities.
Required behavior (MUST)
- Use repositories to reconstitute and persist aggregates.
- Keep infrastructure mapping hidden behind the repository implementation.
- Prefer focused repository methods over giant generic CRUD interfaces when domain intent matters.
- Keep reconstitution paths separate from normal creation paths when that protects invariants.
- Make client code independent of repository implementation details, while repository implementers understand those details.
- Express query criteria as specifications or model concepts when the criteria are domain rules.
- Return domain objects or collections without exposing database structure.
Anti-patterns (MUST NOT)
- Generic repository abstractions that erase domain meaning
- Returning persistence records directly into the domain
- Putting business rules into repository implementations
- Creating one repository per table with no relation to aggregate design
- Letting relational database design dictate object identity, associations, or aggregate boundaries
Factories
Use factories when
- creation is complex
- construction has business rules
- valid creation requires multiple collaborating values
- the creation itself has domain meaning
Rules (MUST unless marked SHOULD or MUST NOT)
- Factories must create valid objects.
- Factories must encode domain creation rules, not technical object assembly.
- Clients and mappers must not contain business construction logic.
- Choose the factory site where creation ownership fits the model.
- Use constructors directly when creation is simple, intention-revealing, and does not expose complex invariants.
- Treat reconstitution from storage separately from new-object creation.
Anti-patterns (MUST NOT)
- Building invalid objects first and fixing them later
- Letting endpoints stitch together aggregates directly
- Using a factory only to hide a trivial constructor
Application Layer
Purpose
The application layer coordinates application tasks.
It does not replace the domain model.
Rules (MUST unless marked SHOULD or MUST NOT)
- Application services load aggregates, call domain behavior, persist results, and coordinate side effects.
- Application services must not hold core business invariants that belong in the domain.
- Application services must speak the ubiquitous language.
- Application services may coordinate transactions and integration publication, but should not become procedural god classes.
Required behavior (MUST)
- Keep each application operation focused on one application action.
- Let domain objects make domain decisions.
- Keep orchestration distinct from business rules.
Anti-patterns (MUST NOT)
- Application services containing all branching business logic
- Application services manipulating entity internals directly
- Repositories, UI handlers, and application services all implementing overlapping rules
Infrastructure
Rules (MUST unless marked SHOULD or MUST NOT)
- Infrastructure is subordinate to the model.
- Object-relational mappings, serializers, external technical clients, delivery mechanisms, messaging details, caches, and framework types must stay out of the domain model.
- Infrastructure must adapt to the model, not the reverse.
- Persistence shape must not define the domain shape.
Anti-patterns (MUST NOT)
- Naming domain concepts after database tables
- Designing aggregates around lazy loading
- Adding methods to entities only because the persistence mechanism needs them
- Letting transport representations become domain objects
Translation at Boundaries
Rules (MUST unless marked SHOULD or MUST NOT)
- Translation is mandatory at context boundaries.
- Translation is usually mandatory between domain objects and transport or persistence representations.
- Anti-corruption layers must preserve the local model rather than mirror foreign models.
- Foreign terms must not silently invade the local ubiquitous language.
Required behavior (MUST)
- Translate external IDs, statuses, and vocabularies explicitly.
- Map transport representations to local commands or domain inputs.
- Keep persistence models and integration models outside the core domain.
Anti-patterns (MUST NOT)
- Passing external API models deep into the domain
- Reusing one representation as delivery input, persistence record, domain object, and integration message
- Adopting vendor status codes as native domain terminology
Supple Design
Rules (MUST unless marked SHOULD or MUST NOT)
- Design interfaces that reveal intention in domain language.
- Prefer side-effect-free functions for calculations and queries.
- Make assertions and invariants explicit in the model.
- Shape objects around conceptual contours, not arbitrary technical convenience.
- Use standalone classes where a concept can be understood without unnecessary dependencies.
- Favor operations that are closed under meaningful domain types when that improves clarity.
- Use declarative design when it makes rules easier to read, combine, and verify.
- Combine specifications with AND, OR, or NOT only while each component meaning remains readable.
- Use subsumption when one specification or category includes another and that relationship matters.
Required behavior (MUST)
- Name methods after what the business is trying to accomplish.
- Separate commands from queries where side effects would surprise readers.
- Put invariant checks where invalid states enter the model.
- Look for cohesive concepts hidden inside long methods, conditionals, or parameter groups.
- Consider a domain-specific language only when it simplifies real domain expression.
Anti-patterns (MUST NOT)
- Technically named APIs that hide intent
- Methods that both ask a question and mutate domain state
- Invariants expressed only in comments or UI/application validation
- Declarative frameworks that obscure rather than clarify business rules
Analysis and Model Patterns
Analysis Patterns
- Use prior domain modeling knowledge when it fits the current domain.
- Do not force an analysis pattern when local language contradicts it.
- Adapt patterns to the bounded context rather than importing them wholesale.
- Search domain literature, prior art, and established formalisms when the team lacks concepts for a good model.
- Use exploration teams for hard modeling problems only when their findings are tested in code and returned to the main team.
Design Patterns in the Model
Use design patterns only when they express the domain model:
Strategy or Policy for interchangeable domain policies.
Composite for part-whole structures that domain experts recognize.
- Avoid patterns that optimize implementation while hiding model meaning.
Required behavior (MUST)
- Reach for established formalisms when the domain already has mature concepts.
- Make pattern names subordinate to domain names.
- Prefer domain-specific names over generic pattern names in public APIs.
Anti-patterns (MUST NOT)
- Applying design patterns because they are familiar rather than because the model needs them
- Naming domain objects after patterns instead of business concepts
- Importing a reference model without validating it against local domain language
Code Generation Rules
When generating code, always do the following in order.
1. Identify the domain concept first
Before writing code, identify:
- the bounded context
- the domain term
- whether the concept is an entity, value object, aggregate, domain service, repository, factory, or specification
- which invariants matter
Do not start from:
- delivery code
- the persistence model
- the database schema
- the REST shape
unless the task is purely infrastructural.
2. Prefer modeling over generic plumbing
If the domain contains real rules:
- put behavior in the model
- introduce value objects
- define aggregate boundaries
- use domain language in APIs
Do not default to procedural services operating on passive records.
3. Use primitives only when they truly carry no domain meaning
Wrap primitives when meaning, validation, unit semantics, or invariants matter.
4. Protect invariants at the model boundary
Do not rely on UI validation, application validation, or repository validation as the primary protection for business rules.
5. Keep the model persistence-ignorant
Do not shape types or boundaries primarily for object-relational mapping convenience.
6. Keep bounded contexts visible in structure
Prefer feature or context ownership in modules and packages.
Avoid architecture that hides business boundaries behind generic folders.
7. Translate foreign models explicitly
Whenever another context, system, transport layer, or persistence format is involved, create translation rather than leakage.
8. Look for implicit concepts
When conditionals, flags, validation blocks, or repeated calculations express business meaning, extract named concepts such as value objects, policies, specifications, or domain services.
9. Preserve strategic priorities
Give the core domain more modeling care than supporting or generic subdomains. Keep context relationships and distillation choices visible when they affect code.
Review Rules
When reviewing or modifying code, actively look for:
Language problems
- vague technical names replacing business terms
- synonyms for one concept
- one term used with multiple meanings
Model problems
- passive entities
- missing value objects
- invalid construction
- missing invariants
- domain logic spread across delivery handlers, application coordination, or repositories
Boundary problems
- bounded context bleeding
- foreign models leaking inward
- shared “common domain” abstractions destroying language clarity
- missing context relationship strategy
- implicit shared kernels with no governance
Aggregate problems
- oversized aggregates
- aggregate roots exposing internal state changes
- direct object references across aggregates where identity should be used
- transactions spanning many aggregates by default
Service problems
- domain services that are really technical helpers
- god services
- application services replacing the whole domain model
Infrastructure problems
- persistence-first modeling
- transport shapes defining the domain
- persistence rules embedded in business logic
Strategic problems
- core domain hidden behind generic infrastructure
- supporting subdomains over-modeled while core logic remains weak
- no visible distillation or large-scale structure where the system complexity requires one
- context map decisions undocumented in code or tests
Testing Rules
Domain tests first
Prioritize tests for:
- entity invariants
- value object validity
- aggregate behavior
- domain services
- specifications and explicit constraints
- application-layer orchestration
- context translation and anticorruption layers
Rules (MUST unless marked SHOULD or MUST NOT)
- Tests must read in the ubiquitous language.
- Tests must verify allowed and forbidden state transitions.
- Tests must verify that invalid objects cannot be created through supported paths.
- Tests must verify translation behavior where anticorruption layers exist.
- Infrastructure tests must stay separate from domain tests.
- Tests for the core domain should read like executable examples of the model.
- Test context boundaries so translations preserve intended meaning.
- Test that one context does not silently break another context's assumptions.
Anti-patterns (MUST NOT)
- Tests named in transport or delivery vocabulary instead of domain vocabulary
- Tests that verify persistence details instead of domain meaning
- Missing tests for invalid transitions and invariant protection
- Tests that validate generic plumbing while leaving core policy untested
Forbidden Patterns
Do not generate or keep these patterns unless explicitly required and justified.
Passive Domain Model
- entities with fields and setters but no real behavior in a complex domain
- all rules living in application services or UI handlers
Smart UI
- UI or application code making domain decisions
- request handlers enforcing core invariants
Persistence-Driven Design
- aggregate boundaries chosen for persistence convenience
- entities shaped around table structures
- domain types depending on persistence mechanics
Primitive Obsession
- raw strings, ints, decimals, and datetimes everywhere for meaningful concepts
- repeated validation logic for the same primitive concept
Shared Model Everything
- one giant shared domain model across contexts
- common abstractions that erase business distinctions
God Services
- single
*Service classes containing many unrelated policies and workflows
- procedural orchestration replacing domain behavior
Invalid Construction
- partially initialized aggregates
- public state changes that bypass invariants
- allowing impossible states because later code will fix them
Fake DDD
- renaming CRUD layers without changing the model
- adding repositories, factories, and services without real domain need
- over-modeling simple supporting subdomains
Context Map Blindness
- integrations with no explicit relationship strategy
- foreign models imported directly into the local core
- shared code treated as neutral when it actually carries another context's language
Pattern-Driven Obscurity
- design patterns that make the domain language harder to see
- frameworks or DSLs that make simple rules harder to verify
- large-scale structures that prevent model evolution
Refactoring Rules
When changing existing code:
- Recover the ubiquitous language.
- Move business rules into entities, value objects, aggregates, or domain services where appropriate.
- Introduce value objects where primitives hide meaning.
- Redraw aggregate boundaries where invariants are unclear or transactional scope is too large.
- Separate bounded contexts that are currently bleeding together.
- Add translation layers where foreign models leak into the domain.
- Break up god services into focused application services plus richer domain behavior.
- Remove persistence and transport assumptions from the model.
- Extract explicit constraints, specifications, and policies from repeated conditionals.
- Clarify context relationships when integration code is ambiguous.
- Distill the core domain out of supporting mechanisms when strategic logic is buried.
- Preserve behavior while improving the model incrementally.
Do not rewrite everything at once unless explicitly required.
Output Expectations
When asked to implement a feature, default to producing:
- bounded context ownership
- domain terms first
- entities or value objects where justified
- aggregates when invariants require a consistency boundary
- specifications or policies when named rules must be evaluated or combined
- repositories for aggregate persistence
- factories when creation is non-trivial
- application services for orchestration
- explicit tra
…(truncated)
1---
2name: book-domain-driven-design-full
3description: >-
4 Domain-Driven Design (Eric Evans) — Full rules — comprehensive mandatory coding standards. Use when asked to apply Domain-Driven Design principles or review code against Domain-Driven Design standards.
5origin: "github.com/ciembor/agent-rules-books (MIT)"
6license: MIT
7version: "1.0.0"
8compatibility: "yana-ai >= 0.14.0"
9metadata:
10 source: https://skillmd.com/skills/yanacuti1121/book-domain-driven-design-full
11---
12
13# OBEY Domain-Driven Design by Eric Evans
14
15## Purpose
16
17This repository follows **Domain-Driven Design**.
18All code generation, modification, and review must optimize for:
19- a precise model of the domain
20- a shared ubiquitous language
21- explicit bounded contexts
22- rich domain behavior where complexity exists
23- disciplined aggregate design
24- protection of invariants
25- clear separation between domain model and supporting infrastructure
26
27This file is a binding engineering policy: `MUST` is binding, `SHOULD` is a strong default, and `MUST NOT` is forbidden.
28
29---
30
31## Primary Directive
32
33When uncertain, prefer the option that makes the **domain model clearer**.
34
35Do not optimize primarily for:
36- fewer files
37- generic reuse
38- CRUD convenience
39- object-relational mapping convenience
40- delivery-layer convenience
41- framework conventions
42- short-term speed at the cost of model clarity
43
44The model must serve the business meaning first.
45
46---
47
48## What DDD Means in This Repository
49
50DDD here does **not** mean:
51- adding layers for ceremony
52- renaming service classes to sound sophisticated
53- wrapping CRUD in verbose abstractions
54- creating entities with only fields and setters
55- turning every concept into an aggregate
56- introducing every DDD pattern everywhere
57- overengineering simple subdomains
58
59DDD here **does** mean:
60- building code around business concepts
61- expressing rules in domain language
62- making context boundaries explicit
63- protecting invariants with the model
64- modeling identity, value, lifecycle, and consistency deliberately
65- translating explicitly across context boundaries
66- simplifying aggressively outside the core domain
67
68---
69
70## Knowledge Crunching and Deep Models
71
72### Rules (MUST unless marked SHOULD or MUST NOT)
731. Treat the model as discovered, not invented from technical structure.
742. Before adding abstractions, identify what domain experts would call the concept.
753. When requirements are ambiguous, look for missing domain distinctions instead of forcing generic names.
764. Let awkward code, contradictory language, and repeated conditionals trigger deeper modeling.
775. Update names and boundaries when new domain insight appears.
78
79### Required behavior (MUST)
80- Ask what business rule, policy, lifecycle, or invariant the code is expressing.
81- Prefer a deeper model that clarifies behavior over a shallow model that merely stores data.
82- Capture newly discovered concepts in names, tests, APIs, and modules.
83- Treat refactoring as part of model discovery, not just code cleanup.
84
85### Anti-patterns (MUST NOT)
86- Starting from database tables and calling the result the domain model
87- Preserving vague names after discovering sharper domain language
88- Hiding domain complexity behind `type`, `status`, or `metadata` fields
89- Treating the first model as final
90
91---
92
93## Model-Driven Design
94
95### Rules (MUST unless marked SHOULD or MUST NOT)
961. The implemented design must reflect the model used in discussion.
972. If the model cannot guide code, refine the model or the code until they align.
983. Domain objects must represent behavior and meaning, not just persistence state.
994. Keep modelers close to implementation. Do not separate analysis from coding so far that the model becomes theoretical.
100
101### Required behavior (MUST)
102- Make important model concepts visible in classes, functions, modules, tests, and interfaces.
103- Prefer executable examples and tests over disconnected documentation.
104- Keep diagrams and documents lightweight, current, and tied to code.
105- Use explanatory models only to teach or reason; do not confuse them with the implementation model unless they are intended to drive code.
106
107### Anti-patterns (MUST NOT)
108- A design document that uses different names than the code
109- Analysts producing models that developers cannot or do not implement
110- Code that follows framework conventions while ignoring the domain model
111- Diagrams that become authoritative after the code and domain understanding have changed
112
113---
114
115## Breakthrough and Deeper Insight
116
117### Rules (MUST unless marked SHOULD or MUST NOT)
1181. Expect useful models to change after deeper insight.
1192. Treat a breakthrough model as a candidate for deliberate refactoring, not as churn.
1203. When a better model appears, compare its explanatory power against migration cost.
1214. Preserve working behavior while moving toward the deeper model in safe steps.
122
123### Required behavior (MUST)
124- Look for concepts that simplify many special cases at once.
125- Prefer changes that make future business rules easier to express.
126- Use awkwardness, contradictions, and repeated failed attempts as signals that the model is shallow.
127- Keep focus on the basics when the model becomes too elaborate.
128
129### Anti-patterns (MUST NOT)
130- Rejecting a better model only because the current one already works
131- Big-bang rewrites when incremental migration is possible
132- Elaborate abstractions that do not improve domain insight
133
134---
135
136## Making Implicit Concepts Explicit
137
138### Rules (MUST unless marked SHOULD or MUST NOT)
1391. Listen for domain language that is not represented in code.
1402. Scrutinize awkward APIs, repeated branches, and contradictory names.
1413. Read domain references, policies, regulations, and prior art when available.
1424. Try multiple model shapes before settling on one for complex concepts.
143
144### Required behavior (MUST)
145- Promote hidden constraints, policies, and processes into explicit domain concepts.
146- Name the concept before choosing the implementation form.
147- Prefer clear domain objects over anonymous helpers when behavior has business meaning.
148
149### Anti-patterns (MUST NOT)
150- Burying business rules in comments
151- Treating contradictions as edge cases instead of modeling signals
152- Keeping vague technical flags after discovering the real concept
153
154---
155
156## Ubiquitous Language
157
158### Rules (MUST unless marked SHOULD or MUST NOT)
1591. Use the exact business terms used by domain experts inside a bounded context.
1602. One concept must have one name inside a bounded context.
1613. One name must not mean different concepts inside a bounded context.
1624. Method names, test names, and modules must use the same vocabulary as the domain.
1635. Rename code when the domain understanding improves.
164
165### Required behavior (MUST)
166- Prefer names from the active bounded context; in a shipping model, terms such as `Cargo`, `Itinerary`, `Handling Event`, and `Route Specification` should appear directly.
167- Prefer operation names that express the domain action, such as changing a cargo destination, adding a handling event, checking allocation, or applying an overbooking policy.
168- Avoid technical placeholders when a precise domain term exists.
169- Avoid names imported from another bounded context without translation.
170
171### Anti-patterns (MUST NOT)
172- Using technical names where the business has precise names
173- Using synonyms for the same concept in the same context
174- Reusing the same term for different meanings because it is convenient
175- Keeping bad names because they already exist in the database
176
177---
178
179## Communication Artifacts
180
181### Rules (MUST unless marked SHOULD or MUST NOT)
1821. Documents and diagrams must support the ubiquitous language.
1832. Written design material must be short enough to stay maintained.
1843. Executable tests are preferred for rules that can be verified.
1854. Diagrams should emphasize boundaries, relationships, invariants, and lifecycle over class inventory.
186
187### Required behavior (MUST)
188- Use examples and scenario tests as living documentation.
189- Keep glossary-like explanations close to the bounded context they describe.
190- Update documents when terminology or context boundaries change.
191
192### Anti-patterns (MUST NOT)
193- Long design documents that drift away from code
194- Diagrams that show every class but hide the model's meaning
195- Documentation that introduces vocabulary not used by code or tests
196
197---
198
199## Scenario Walkthroughs
200
201### Rules (MUST unless marked SHOULD or MUST NOT)
2021. Validate the model by walking through real application scenarios.
2032. Use scenarios to test whether entities, value objects, aggregates, repositories, and factories collaborate naturally.
2043. When a scenario feels procedural or awkward, look for missing model concepts or wrong boundaries.
2054. Revisit aggregate and module boundaries after scenario walkthroughs reveal pressure.
206
207### Required behavior (MUST)
208- Prefer examples that exercise real business decisions, not only CRUD paths.
209- Use scenarios to verify object creation, lifecycle transitions, and cross-context translation.
210- Let performance tuning follow model clarity; do not distort the model prematurely for optimization.
211
212### Anti-patterns (MUST NOT)
213- Designing model elements only in isolation
214- Treating scenario code as an afterthought after infrastructure is complete
215- Optimizing persistence paths before the model expresses the business correctly
216
217---
218
219## Layered Architecture and Smart UI
220
221### Rules (MUST unless marked SHOULD or MUST NOT)
2221. Keep the domain layer as the place where the model and business rules live.
2232. Separate presentation, application coordination, domain behavior, and infrastructure when the domain is complex enough to need model-driven design.
2243. Let application code coordinate tasks without owning domain decisions.
2254. Keep infrastructure services and framework concerns outside domain objects.
2265. Use Smart UI only for simple applications where rich domain abstraction, reuse, integration, and deep business rules are not important.
227
228### Anti-patterns (MUST NOT)
229- UI screens, database tables, or framework annotations defining the domain vocabulary
230- UI, application coordination, jobs, or scripts carrying domain rules while domain objects stay passive
231- choosing Smart UI when the business behavior needs reuse or abstraction
232
233---
234
235## Bounded Contexts
236
237### Rules (MUST unless marked SHOULD or MUST NOT)
2381. Every substantial domain area must belong to a clearly identified bounded context.
2392. A model is valid only inside its own bounded context.
2403. Concepts from another context must not be imported directly as if they were native.
2414. Translation across contexts must be explicit.
2425. Shared models across multiple contexts are forbidden unless intentionally governed as a shared kernel.
243
244### Required behavior (MUST)
245- Keep package, module, or namespace ownership explicit.
246- Model `Customer` separately in different contexts if meanings differ.
247- Prefer context-specific contracts, IDs, published language, or anticorruption layers over shared classes.
248
249### Anti-patterns (MUST NOT)
250- One giant company-wide domain model
251- A `shared/domain` package that erases boundaries
252- Copying foreign terms into the local model without translation
253- Reusing one aggregate type across unrelated contexts
254
255---
256
257## Strategic Design
258
259### Core Domain
2601. Invest the most care in the core domain.
2612. Protect the core domain from foreign models, vendor schemas, and generic abstractions.
2623. Keep the core domain expressive even if supporting areas are simpler.
263
264### Supporting and Generic Subdomains
2651. Do not over-model commodity concerns.
2662. Use simpler models where business complexity is low.
2673. Save the richest modeling effort for the parts that matter strategically.
268
269### Context Mapping
2701. Integration relationships must be visible in code.
2712. Ownership of translation must be explicit.
2723. Upstream and downstream influence must be reflected in adapters and contracts.
273
274### Anti-patterns (MUST NOT)
275- Spending more design effort on plumbing than on the core domain
276- Modeling authentication utilities more richly than the pricing engine
277- Allowing a legacy system vocabulary to dominate the core model
278
279---
280
281## Model Integrity Patterns
282
283### Continuous Integration Within a Context
2841. A bounded context must keep one internally consistent model.
2852. Team members working in the same context must integrate terminology and model changes continuously.
2863. Conflicting meanings inside one context must be resolved quickly through naming, tests, and refactoring.
287
288### Context Relationships
289Use context relationship patterns intentionally:
290- `Shared Kernel` only for a small, jointly governed model subset.
291- `Customer/Supplier` when an upstream team commits to downstream needs.
292- `Conformist` only when adopting the upstream model is cheaper than translating it.
293- `Anticorruption Layer` when protecting the local model from a foreign or legacy model.
294- `Separate Ways` when integration cost is higher than shared capability value.
295- `Open Host Service` when a context exposes a stable integration protocol.
296- `Published Language` when contexts need a documented exchange language.
297
298### Context Transformations
2991. Move from Separate Ways to Shared Kernel only when the overlap is small, valuable, and worth coordination.
3002. Move from Shared Kernel to Continuous Integration only when teams are ready to share one model frequently.
3013. Phase out legacy systems by protecting the new model and replacing responsibilities incrementally through translations.
3024. Evolve Open Host Service toward Published Language when interchange stability is needed beyond one service.
303
304### Required behavior (MUST)
305- Make context maps visible in package structure, integration adapters, documentation, or tests.
306- Name adapters after the relationship they implement when that improves clarity.
307- Keep foreign model terms out of the local core unless deliberately accepted as conformist.
308
309### Anti-patterns (MUST NOT)
310- Accidental shared kernels with no ownership rules
311- Calling every integration an anticorruption layer without translation
312- Letting upstream APIs silently define downstream domain language
313- Treating context mapping as architecture documentation only, not code structure
314
315---
316
317## Distillation
318
319### Core Domain
3201. Identify the part of the model that creates strategic advantage.
3212. Put the strongest modeling effort and cleanest design into that core.
3223. Do not bury the core under generic mechanisms, infrastructure, or broad shared abstractions.
323
324### Distillation Patterns
325Use these patterns when they clarify priority and investment:
326- `Domain Vision Statement` for a short statement of the core model's purpose.
327- `Highlighted Core` to mark the most important elements inside a larger model.
328- `Generic Subdomain` for commodity capabilities that do not deserve rich custom modeling.
329- `Cohesive Mechanism` for technical mechanisms that can be separated from domain policy.
330- `Segregated Core` when the core is tangled with supporting concerns.
331- `Abstract Core` when related specialized models need a stable conceptual foundation.
332
333### Required behavior (MUST)
334- Make the core domain easy to find in code.
335- Keep supporting and generic subdomains simpler unless their complexity is real.
336- Choose refactoring targets based on strategic importance, not just local messiness.
337
338### Anti-patterns (MUST NOT)
339- Spending equal modeling effort on every subsystem
340- Letting technical mechanisms dominate the core model
341- Hiding the core behind generic shared packages
342- Refactoring peripheral code while the core remains unclear
343
344---
345
346## Large-Scale Structure
347
348### Rules (MUST unless marked SHOULD or MUST NOT)
3491. Large-scale structure should help people understand the system, not freeze it.
3502. Let structure evolve as the model evolves.
3513. Use a guiding structure only when it reduces cognitive load across contexts.
3524. Keep the structure minimally restrictive.
353
354### Patterns
355Use these patterns deliberately:
356- `Evolving Order` when structure must emerge through iterative modeling.
357- `System Metaphor` only when it genuinely clarifies the model.
358- `Responsibility Layers` when responsibilities naturally stratify across the system.
359- `Knowledge Level` when rules or policies must be represented explicitly and changed by configuration or data.
360- `Pluggable Component Framework` when variation points are stable and worth formalizing.
361
362### Required behavior (MUST)
363- Combine bounded contexts, distillation, and large-scale structure into one coherent strategy.
364- Revisit structure when it no longer fits the model.
365- Prefer communication and self-discipline over heavy structural machinery where possible.
366
367### Anti-patterns (MUST NOT)
368- A master plan that blocks model learning
369- A metaphor that sounds clever but misleads design decisions
370- Overly restrictive layers that fight the domain
371- Framework architecture masquerading as domain structure
372
373---
374
375## Strategic Decision Making
376
377### Rules (MUST unless marked SHOULD or MUST NOT)
3781. Assess the current model and context map before prescribing a strategic structure.
3792. Decide who owns strategic design choices explicitly.
3803. Let application development inform strategy; do not impose strategy detached from implementation feedback.
3814. Architecture teams must stay customer-focused and model-focused, not framework-focused.
3825. Strategic decisions must remain revisable as domain understanding changes.
383
384### Required behavior (MUST)
385- Combine bounded contexts with distillation and large-scale structure when system complexity requires it.
386- Make strategy visible enough that teams can coordinate without a rigid master plan.
387- Keep technical frameworks subordinate to the domain strategy.
388- Treat strategic design as team decision-making, not just diagram production.
389
390### Anti-patterns (MUST NOT)
391- A top-down master plan that ignores model learning
392- Strategy owned by people disconnected from implementation
393- Technical architecture decisions presented as domain strategy
394- Context maps, core-domain decisions, and large-scale structures that are never revisited
395
396---
397
398## Entities
399
400### Use entities when
401- identity matters over time
402- lifecycle matters
403- continuity matters beyond current attributes
404- business rules depend on “which one” rather than only “what value”
405
406### Rules (MUST unless marked SHOULD or MUST NOT)
4071. Entities must have explicit identity.
4082. Entities must protect their own valid state transitions.
4093. Entities must expose intention-revealing behavior, not arbitrary state changes.
4104. Entities must not be treated as passive records in behavior-rich domains.
411
412### Required behavior (MUST)
413- Prefer methods that tell an entity what domain action to perform.
414- In a shipping model, express destination changes and handling-event additions as model operations rather than procedural data edits.
415- Hide direct state changes behind methods that encode domain meaning.
416- Keep identity stable and explicit.
417
418### Anti-patterns (MUST NOT)
419- Public setters for every field
420- Application services manually editing all entity state
421- UI or application code deciding which transitions are valid
422- Entities used only as persistence shells
423
424---
425
426## Value Objects
427
428### Use value objects when
429- a concept is defined by attributes rather than identity
430- the concept has validation rules
431- the concept has behavior
432- passing a primitive would hide meaning
433
434### Rules (MUST unless marked SHOULD or MUST NOT)
4351. Value objects must be immutable by default.
4362. Construction must guarantee validity.
4373. Equality must be by value, not by identity.
4384. Validation for the concept should live inside the value object.
4395. Replace primitive obsession aggressively where the concept matters.
440
441### Required behavior (MUST)
442- Use value objects for descriptive concepts whose attributes together carry domain meaning.
443- Name value objects after the domain concept, not the primitive representation.
444- Keep validation and side-effect-free operations for the value near the value itself.
445- Replace raw primitives when a named quantity, range, code, measurement, or descriptive whole value matters to the model.
446
447### Anti-patterns (MUST NOT)
448- Repeating the same value validation across handlers
449- Passing raw primitives for named domain quantities, ranges, codes, or measurements
450- Passing raw strings for meaningful identifiers
451- Letting invalid values exist temporarily without an explicit model for incompleteness
452
453---
454
455## Associations and Modules
456
457### Associations
4581. Model associations only when they support behavior or meaning.
4592. Prefer simpler, more navigable associations over fully connected object graphs.
4603. Reduce bidirectional associations unless the domain requires them.
4614. Reference other aggregates by identity unless direct object traversal is part of an invariant boundary.
462
463### Modules
4641. Modules must communicate domain concepts and bounded context ownership.
4652. Organize modules around model meaning, not only technical layers.
4663. Keep related concepts together when they change together.
4674. Avoid infrastructure-driven packaging that hides the domain.
468
469### Required behavior (MUST)
470- Use package names that match the ubiquitous language.
471- Keep model concepts discoverable from the directory structure.
472- Split modules when different concepts evolve independently.
473
474### Anti-patterns (MUST NOT)
475- `models`, `services`, `utils`, and `helpers` as the dominant structure
476- Associations created only because the persistence mechanism supports them
477- Object graphs that make aggregate boundaries invisible
478- Modules grouped by technical artifact while domain concepts are scattered
479
480---
481
482## Aggregates
483
484### Purpose
485Aggregates are **consistency boundaries**, not just object graphs.
486
487### Rules (MUST unless marked SHOULD or MUST NOT)
4881. Design aggregates around invariants that must be consistent immediately.
4892. Keep aggregates as small as possible.
4903. All modifications that affect aggregate invariants must go through the aggregate root.
4914. Reference other aggregates by identity unless stronger consistency is truly required.
4925. Keep transactional boundaries aligned with invariants; do not expand transactions across aggregates merely for convenience.
493
494### Required behavior (MUST)
495- Put invariant-protecting methods on the aggregate root.
496- Keep internal members encapsulated.
497- Handle consistency across aggregate boundaries deliberately when the invariant does not belong inside one aggregate.
498- Model transactional boundaries deliberately.
499
500### Anti-patterns (MUST NOT)
501- Large graph aggregates built for object-relational mapping convenience
502- Aggregate roots exposing internal collections for arbitrary external state changes
503- Transactions modifying many aggregates because object references make it easy
504- Confusing parent-child object structure with aggregate boundaries
505
506---
507
508## Domain Services
509
510### Use a domain service only when
511- the behavior is domain-significant
512- the behavior does not naturally belong on one entity or value object
513- the operation still belongs to the ubiquitous language
514
515### Rules (MUST unless marked SHOULD or MUST NOT)
5161. A domain service must express a domain concept, not a technical convenience.
5172. If behavior clearly belongs to an entity or value object, keep it there.
5183. Do not move behavior into services merely to keep entities thin.
519
520### Required behavior (MUST)
521- Domain services should sound like the business.
522- Domain services should coordinate domain concepts, not infrastructure details.
523
524### Anti-patterns (MUST NOT)
525- a single `*Service` containing all rules for a model area
526- a service containing dozens of unrelated policies
527- “Domain services” that are only wrappers for repositories or external technical clients
528- Extracting behavior from entities prematurely
529
530---
531
532## Explicit Concepts and Specifications
533
534### Rules (MUST unless marked SHOULD or MUST NOT)
5351. Make implicit constraints explicit in the model.
5362. Model domain processes as domain objects when the process has business meaning.
5373. Use specifications for named, combinable business rules that answer whether something satisfies a criterion.
5384. Keep specifications in domain language, not query language.
539
540### Required behavior (MUST)
541- Extract repeated conditionals into named domain concepts.
542- Prefer named concepts such as route specifications, overbooking policies, or allocation rules over anonymous boolean expressions.
543- Keep persistence querying concerns separate from domain specifications unless the project deliberately provides translation.
544- Use specifications to clarify policy, validation, selection, and compatibility rules.
545
546### Anti-patterns (MUST NOT)
547- Complex business conditions duplicated across services
548- Boolean flags that hide a named domain rule
549- Specifications that are just persistence query builders
550- Processes represented only as scripts or transaction handlers when the business treats them as concepts
551
552---
553
554## Repositories
555
556### Purpose
557Repositories provide access to aggregates as part of the model.
558
559### Rules (MUST unless marked SHOULD or MUST NOT)
5601. Repositories exist for aggregate roots, not for every table.
5612. Repository interfaces must be defined by the domain or application model that uses them.
5623. Repositories must return domain objects or domain-oriented results.
5634. Repository contracts must reflect intent where useful.
5645. Repositories must not become universal query utilities.
565
566### Required behavior (MUST)
567- Use repositories to reconstitute and persist aggregates.
568- Keep infrastructure mapping hidden behind the repository implementation.
569- Prefer focused repository methods over giant generic CRUD interfaces when domain intent matters.
570- Keep reconstitution paths separate from normal creation paths when that protects invariants.
571- Make client code independent of repository implementation details, while repository implementers understand those details.
572- Express query criteria as specifications or model concepts when the criteria are domain rules.
573- Return domain objects or collections without exposing database structure.
574
575### Anti-patterns (MUST NOT)
576- Generic repository abstractions that erase domain meaning
577- Returning persistence records directly into the domain
578- Putting business rules into repository implementations
579- Creating one repository per table with no relation to aggregate design
580- Letting relational database design dictate object identity, associations, or aggregate boundaries
581
582---
583
584## Factories
585
586### Use factories when
587- creation is complex
588- construction has business rules
589- valid creation requires multiple collaborating values
590- the creation itself has domain meaning
591
592### Rules (MUST unless marked SHOULD or MUST NOT)
5931. Factories must create valid objects.
5942. Factories must encode domain creation rules, not technical object assembly.
5953. Clients and mappers must not contain business construction logic.
5964. Choose the factory site where creation ownership fits the model.
5975. Use constructors directly when creation is simple, intention-revealing, and does not expose complex invariants.
5986. Treat reconstitution from storage separately from new-object creation.
599
600### Anti-patterns (MUST NOT)
601- Building invalid objects first and fixing them later
602- Letting endpoints stitch together aggregates directly
603- Using a factory only to hide a trivial constructor
604
605## Application Layer
606
607### Purpose
608The application layer coordinates application tasks.
609It does not replace the domain model.
610
611### Rules (MUST unless marked SHOULD or MUST NOT)
6121. Application services load aggregates, call domain behavior, persist results, and coordinate side effects.
6132. Application services must not hold core business invariants that belong in the domain.
6143. Application services must speak the ubiquitous language.
6154. Application services may coordinate transactions and integration publication, but should not become procedural god classes.
616
617### Required behavior (MUST)
618- Keep each application operation focused on one application action.
619- Let domain objects make domain decisions.
620- Keep orchestration distinct from business rules.
621
622### Anti-patterns (MUST NOT)
623- Application services containing all branching business logic
624- Application services manipulating entity internals directly
625- Repositories, UI handlers, and application services all implementing overlapping rules
626
627---
628
629## Infrastructure
630
631### Rules (MUST unless marked SHOULD or MUST NOT)
6321. Infrastructure is subordinate to the model.
6332. Object-relational mappings, serializers, external technical clients, delivery mechanisms, messaging details, caches, and framework types must stay out of the domain model.
6343. Infrastructure must adapt to the model, not the reverse.
6354. Persistence shape must not define the domain shape.
636
637### Anti-patterns (MUST NOT)
638- Naming domain concepts after database tables
639- Designing aggregates around lazy loading
640- Adding methods to entities only because the persistence mechanism needs them
641- Letting transport representations become domain objects
642
643---
644
645## Translation at Boundaries
646
647### Rules (MUST unless marked SHOULD or MUST NOT)
6481. Translation is mandatory at context boundaries.
6492. Translation is usually mandatory between domain objects and transport or persistence representations.
6503. Anti-corruption layers must preserve the local model rather than mirror foreign models.
6514. Foreign terms must not silently invade the local ubiquitous language.
652
653### Required behavior (MUST)
654- Translate external IDs, statuses, and vocabularies explicitly.
655- Map transport representations to local commands or domain inputs.
656- Keep persistence models and integration models outside the core domain.
657
658### Anti-patterns (MUST NOT)
659- Passing external API models deep into the domain
660- Reusing one representation as delivery input, persistence record, domain object, and integration message
661- Adopting vendor status codes as native domain terminology
662
663---
664
665## Supple Design
666
667### Rules (MUST unless marked SHOULD or MUST NOT)
6681. Design interfaces that reveal intention in domain language.
6692. Prefer side-effect-free functions for calculations and queries.
6703. Make assertions and invariants explicit in the model.
6714. Shape objects around conceptual contours, not arbitrary technical convenience.
6725. Use standalone classes where a concept can be understood without unnecessary dependencies.
6736. Favor operations that are closed under meaningful domain types when that improves clarity.
6747. Use declarative design when it makes rules easier to read, combine, and verify.
6758. Combine specifications with AND, OR, or NOT only while each component meaning remains readable.
6769. Use subsumption when one specification or category includes another and that relationship matters.
677
678### Required behavior (MUST)
679- Name methods after what the business is trying to accomplish.
680- Separate commands from queries where side effects would surprise readers.
681- Put invariant checks where invalid states enter the model.
682- Look for cohesive concepts hidden inside long methods, conditionals, or parameter groups.
683- Consider a domain-specific language only when it simplifies real domain expression.
684
685### Anti-patterns (MUST NOT)
686- Technically named APIs that hide intent
687- Methods that both ask a question and mutate domain state
688- Invariants expressed only in comments or UI/application validation
689- Declarative frameworks that obscure rather than clarify business rules
690
691---
692
693## Analysis and Model Patterns
694
695### Analysis Patterns
6961. Use prior domain modeling knowledge when it fits the current domain.
6972. Do not force an analysis pattern when local language contradicts it.
6983. Adapt patterns to the bounded context rather than importing them wholesale.
6994. Search domain literature, prior art, and established formalisms when the team lacks concepts for a good model.
7005. Use exploration teams for hard modeling problems only when their findings are tested in code and returned to the main team.
701
702### Design Patterns in the Model
703Use design patterns only when they express the domain model:
704- `Strategy` or `Policy` for interchangeable domain policies.
705- `Composite` for part-whole structures that domain experts recognize.
706- Avoid patterns that optimize implementation while hiding model meaning.
707
708### Required behavior (MUST)
709- Reach for established formalisms when the domain already has mature concepts.
710- Make pattern names subordinate to domain names.
711- Prefer domain-specific names over generic pattern names in public APIs.
712
713### Anti-patterns (MUST NOT)
714- Applying design patterns because they are familiar rather than because the model needs them
715- Naming domain objects after patterns instead of business concepts
716- Importing a reference model without validating it against local domain language
717
718---
719
720## Code Generation Rules
721
722When generating code, always do the following in order.
723
724### 1. Identify the domain concept first
725Before writing code, identify:
726- the bounded context
727- the domain term
728- whether the concept is an entity, value object, aggregate, domain service, repository, factory, or specification
729- which invariants matter
730
731Do not start from:
732- delivery code
733- the persistence model
734- the database schema
735- the REST shape
736unless the task is purely infrastructural.
737
738### 2. Prefer modeling over generic plumbing
739If the domain contains real rules:
740- put behavior in the model
741- introduce value objects
742- define aggregate boundaries
743- use domain language in APIs
744
745Do not default to procedural services operating on passive records.
746
747### 3. Use primitives only when they truly carry no domain meaning
748Wrap primitives when meaning, validation, unit semantics, or invariants matter.
749
750### 4. Protect invariants at the model boundary
751Do not rely on UI validation, application validation, or repository validation as the primary protection for business rules.
752
753### 5. Keep the model persistence-ignorant
754Do not shape types or boundaries primarily for object-relational mapping convenience.
755
756### 6. Keep bounded contexts visible in structure
757Prefer feature or context ownership in modules and packages.
758Avoid architecture that hides business boundaries behind generic folders.
759
760### 7. Translate foreign models explicitly
761Whenever another context, system, transport layer, or persistence format is involved, create translation rather than leakage.
762
763### 8. Look for implicit concepts
764When conditionals, flags, validation blocks, or repeated calculations express business meaning, extract named concepts such as value objects, policies, specifications, or domain services.
765
766### 9. Preserve strategic priorities
767Give the core domain more modeling care than supporting or generic subdomains. Keep context relationships and distillation choices visible when they affect code.
768
769---
770
771## Review Rules
772
773When reviewing or modifying code, actively look for:
774
775### Language problems
776- vague technical names replacing business terms
777- synonyms for one concept
778- one term used with multiple meanings
779
780### Model problems
781- passive entities
782- missing value objects
783- invalid construction
784- missing invariants
785- domain logic spread across delivery handlers, application coordination, or repositories
786
787### Boundary problems
788- bounded context bleeding
789- foreign models leaking inward
790- shared “common domain” abstractions destroying language clarity
791- missing context relationship strategy
792- implicit shared kernels with no governance
793
794### Aggregate problems
795- oversized aggregates
796- aggregate roots exposing internal state changes
797- direct object references across aggregates where identity should be used
798- transactions spanning many aggregates by default
799
800### Service problems
801- domain services that are really technical helpers
802- god services
803- application services replacing the whole domain model
804
805### Infrastructure problems
806- persistence-first modeling
807- transport shapes defining the domain
808- persistence rules embedded in business logic
809
810### Strategic problems
811- core domain hidden behind generic infrastructure
812- supporting subdomains over-modeled while core logic remains weak
813- no visible distillation or large-scale structure where the system complexity requires one
814- context map decisions undocumented in code or tests
815
816---
817
818## Testing Rules
819
820### Domain tests first
821Prioritize tests for:
822- entity invariants
823- value object validity
824- aggregate behavior
825- domain services
826- specifications and explicit constraints
827- application-layer orchestration
828- context translation and anticorruption layers
829
830### Rules (MUST unless marked SHOULD or MUST NOT)
8311. Tests must read in the ubiquitous language.
8322. Tests must verify allowed and forbidden state transitions.
8333. Tests must verify that invalid objects cannot be created through supported paths.
8344. Tests must verify translation behavior where anticorruption layers exist.
8355. Infrastructure tests must stay separate from domain tests.
8366. Tests for the core domain should read like executable examples of the model.
8377. Test context boundaries so translations preserve intended meaning.
8388. Test that one context does not silently break another context's assumptions.
839
840### Anti-patterns (MUST NOT)
841- Tests named in transport or delivery vocabulary instead of domain vocabulary
842- Tests that verify persistence details instead of domain meaning
843- Missing tests for invalid transitions and invariant protection
844- Tests that validate generic plumbing while leaving core policy untested
845
846---
847
848## Forbidden Patterns
849
850Do not generate or keep these patterns unless explicitly required and justified.
851
852### Passive Domain Model
853- entities with fields and setters but no real behavior in a complex domain
854- all rules living in application services or UI handlers
855
856### Smart UI
857- UI or application code making domain decisions
858- request handlers enforcing core invariants
859
860### Persistence-Driven Design
861- aggregate boundaries chosen for persistence convenience
862- entities shaped around table structures
863- domain types depending on persistence mechanics
864
865### Primitive Obsession
866- raw strings, ints, decimals, and datetimes everywhere for meaningful concepts
867- repeated validation logic for the same primitive concept
868
869### Shared Model Everything
870- one giant shared domain model across contexts
871- common abstractions that erase business distinctions
872
873### God Services
874- single `*Service` classes containing many unrelated policies and workflows
875- procedural orchestration replacing domain behavior
876
877### Invalid Construction
878- partially initialized aggregates
879- public state changes that bypass invariants
880- allowing impossible states because later code will fix them
881
882### Fake DDD
883- renaming CRUD layers without changing the model
884- adding repositories, factories, and services without real domain need
885- over-modeling simple supporting subdomains
886
887### Context Map Blindness
888- integrations with no explicit relationship strategy
889- foreign models imported directly into the local core
890- shared code treated as neutral when it actually carries another context's language
891
892### Pattern-Driven Obscurity
893- design patterns that make the domain language harder to see
894- frameworks or DSLs that make simple rules harder to verify
895- large-scale structures that prevent model evolution
896
897---
898
899## Refactoring Rules
900
901When changing existing code:
902
9031. Recover the ubiquitous language.
9042. Move business rules into entities, value objects, aggregates, or domain services where appropriate.
9053. Introduce value objects where primitives hide meaning.
9064. Redraw aggregate boundaries where invariants are unclear or transactional scope is too large.
9075. Separate bounded contexts that are currently bleeding together.
9086. Add translation layers where foreign models leak into the domain.
9097. Break up god services into focused application services plus richer domain behavior.
9108. Remove persistence and transport assumptions from the model.
9119. Extract explicit constraints, specifications, and policies from repeated conditionals.
91210. Clarify context relationships when integration code is ambiguous.
91311. Distill the core domain out of supporting mechanisms when strategic logic is buried.
91412. Preserve behavior while improving the model incrementally.
915
916Do not rewrite everything at once unless explicitly required.
917
918---
919
920## Output Expectations
921
922When asked to implement a feature, default to producing:
923- bounded context ownership
924- domain terms first
925- entities or value objects where justified
926- aggregates when invariants require a consistency boundary
927- specifications or policies when named rules must be evaluated or combined
928- repositories for aggregate persistence
929- factories when creation is non-trivial
930- application services for orchestration
931- explicit translation at external boundaries
932- visible context relationship choices when integrating with other models
933- simpler supporting or generic subdomain designs when rich modeling is not justified
934
935When asked to review code:
936- identify model-language mismatch
937- identify missing value objects
938- identify passive data-structure model symptoms
939- identify bad aggregate boundaries
940- identify context leakage
941- identify infrastructure-driven modeling
942- identify missing explicit constraints or specifications
943- identify weak core-domain distillation
944- identify context map and large-scale structure problems
945- propose concrete DDD refactorings
946
947When asked to modify code:
948- improve the model first where safe
949- do not deepen technical shortcuts that weaken the domain language
950- keep business meaning more explicit after the change than before it
951- preserve the model's strategic priorities
952
953---
954
955## Review Checklist
956
957Before finalizing any change, verify:
958
959- Is the bounded context clear?
960- Does the code use the ubiquitous language consistently?
961- Are important concepts modeled explicitly?
962- Are value objects used where primitives hide meaning?
963- Are entities protecting valid transitions?
964- Are aggregate boundaries clear and small enough?
965- Are cross-aggregate references by identity unless stronger consistency is required?
966- Are repositories aligned to aggregates rather than tables?
967- Are specifications, policies, or explicit constraints used where repeated rules need names?
968- Are application services orchestrating rather than owning all rules?
969- Is the domain model protected from transport, persistence, and vendor models?
970- Are context boundaries translated explicitly?
971- Is the context map relationship clear for integrations?
972- Is the core domain visible and protected from generic mechanisms?
973- Are large-scale structures helping rather than freezing the model?
974- Did we avoid god services?
975- Did we avoid passive domain objects where the domain is complex?
976- Did we avoid over-modeling where the domain is simple?
977
978If any answer is no, revise before shipping.
979
980---
981
982## Final Instruction
983
984When uncertain, choose the option that:
9851. makes the domain language sharper
9862. protects invariants inside the model
9873. keeps bounded contexts explicit
9884. reduces primitive obsession
9895. keeps infrastructure subordinate to domain meaning
990
991Reject changes that make the code more generic but the domain less clear.