Chapter 21·Practice·Anti-Patterns and Common Mistakes
Anti-Patterns and Common Mistakes
Anemic model, Primitive Obsession, oversized aggregate, a database shared between Bounded Contexts, mutable events, and over-engineering. For each anti-pattern, the chapter shows how to spot it in code and how to get rid of it.
AuthorM. Katuščák
Reading time≈ 27 min
Difficulty
intermediate
Published · Updated·
In this chapter
In this chapter
21.01 Introduction: why anti-patterns are worth knowing#
What follows is a catalog of code and modeling anti-patterns in DDD. Operational and infrastructure
friction (Doctrine, Messenger, ACL to external APIs, Symfony Form vs. Command) is covered in
DDD in Practice – Where It Hurts; the decision whether to use DDD at all
belongs to When Not to Use DDD.
Teams starting with DDD keep running into the same mistakes, even when they understand the theory. The terms used here (entity, value object, aggregate, Bounded Context) are defined in DDD Building Blocks.
An anti-pattern is an approach developers slide into naturally. It looks right, but it violates DDD principles and, over time, undermines maintainability, testability, and performance. That is why each section below carries two things. The telltale sign is a sentence that tells you whether the problem affects your code. The boundary then marks where the criticized practice stops being a mistake.
The best-known DDD anti-pattern is not here. Big Ball of Mud, an area with no recognizable boundaries, belongs to Context Mapping, because it can be deliberately fenced off and left alone; it is covered in Anti-pattern: Big Ball of Mud.
The anemic model is one of the most common anti-patterns in object-oriented development, and in DDD it hurts in particular. Martin Fowler popularized the term in a 2003 article [1]. Domain classes (entities, aggregates) serve only as data containers. They contain nothing but getters and setters, and all domain logic sits in the service layer.
To the argument from OOP principles, Fowler added a second one, about cost: the anemic model carries all the costs of a domain model without delivering its benefits. You pay for database mapping, wrapping values, and splitting code into layers, and you get a data structure a plain SELECT could have served. The problem is this bill with nothing in return, not a broken rule of OOP.
Telltale sign. In Implementing Domain-Driven Design (2013), Vaughn Vernon offers a diagnostic test of two questions. Paraphrased: does your entity have only getters and setters, and does the rule that works with its data live in some other class? Two “yes” answers mean anemia. The test is more useful than the definition, because you can apply it directly to a specific file.
FIG. 21.2-AAnemic vs. rich domain model – where the logic lives
The service layer as such is not the anti-pattern. In the same article, Fowler explicitly defends the Service Layer and rejects only the idea that all domain logic should live in it. Under the name “service,” projects therefore hide three different things:
An application service orchestrates: it loads an aggregate, calls one method on it, saves the result, and dispatches events. It contains no domain rule of its own, and it is fine.
A domain service carries a rule that does not belong to a single aggregate. Such a rule is a calculation across several aggregates or a policy with external input. It is a legitimate building block; see domain services.
A “God service” holds rules that belong to entities, which themselves have no behavior. Only that is the anemic model.
The activate(), deactivate(), and register() methods replace generic setters. Because the entity guards its invariants itself, nobody from outside can push it into an inconsistent state.
When the anemic model is not a mistake
Fowler himself admits that a domain model is not always the best tool and points to Transaction Script [2]. It is a legitimate pattern from Patterns of Enterprise Application Architecture that organizes logic by procedures, one per request. In a domain with five rules, a procedure tends to read better than the six classes around it. The choice between the patterns is part of the decision about the subdomain type; see When Not to Use DDD.
The second objection comes from the functional school. Mark Seemann shows that encapsulation is not the same as a method on an object. The same guarantee comes from a type that cannot be constructed into an invalid state, plus a module of functions over it [3]. Data can be separated from behavior. What cannot be separated is validation from data. A record with public fields that anyone can fill with anything is anemic in the harmful sense, however well the functions over it are written.
Where the rule stops. The anemic model is a mistake when you pay the price of a domain model without its benefit. Once you choose a domain model, the rules belong in it. With Transaction Script, there is no anemia to fear; the decision for it has to be stated explicitly, though, and a Domain/ directory should not pose as a domain model.
Primitive Obsession occurs when developers use primitive data types (string, int, float) where value objects belong. Primitives seem straightforward until validation starts repeating and values get mixed up.
Telltale sign. Find the email validation in your project and count how many places it appears in. Three occurrences of the same filter_var() over the same value mean the value wants its own type.
Money rejects a negative amount on purpose. The direction of the movement is carried by the domain operation, not by the amount: a credit note is a refund() call, not a negative sum, so the sign cannot get lost along the way. The definition is in the Value Objects section; the example above therefore does not repeat it.
A value object has its cost too. It pays off where the value meets at least one of three conditions. It carries its own validity rules (Email, BirthNumber), it has its own operations (Money::add()), or it risks being mixed up with another value of the same primitive type (OrderId vs. UserId). Evans states the criterion from the other side: a value object is an element of the model where you care only about its attributes and logic [6].
Where the rule stops. A note, description, or internalComment field meets none of the conditions. A Note class wrapping a string without a single rule is exactly the ceremony that Anti-pattern: over-engineering in simple applications warns against. The criterion, then, is not the number of primitives in the code, but duplicated validation and the risk of a mix-up.
An aggregate boundary is drawn around transactional consistency, that is, around the smallest group of objects that change together in one transaction. An oversized aggregate (“God Aggregate”) gathers under one root entities and logic that do not belong together transactionally, and in doing so it violates the single responsibility principle. Vernon uses the more sober name large-cluster aggregate for the same thing; the community sticks with the more dramatic “God.”
Telltale sign. Look at the last time an item was added to a collection inside the aggregate. If adding one new row means loading a thousand existing ones, the aggregate boundary follows associations, not invariants.
FIG. 21.4-AGod Aggregate vs. properly split aggregates connected by ID
The rule comes from Vernon's Effective Aggregate Design series [7]. An aggregate holds the root and the necessary minimum of attributes and value-typed properties, nothing more. Vernon adds a point that anti-pattern catalogs usually leave out: aggregates are consistency boundaries, not the result of an effort to design an object graph. If changing one object does not require a consistent change of another in the same transaction, they belong to different aggregates.
Where the rule stops. You can also shrink too far. Vernon names both failures: an aggregate assembled for compositional convenience is too large, while an aggregate broken down into individual entities stops protecting the real invariants. The second mistake is harder to find, because it does not show in performance, only later in inconsistent data.
In Doctrine, the most common cause of a large aggregate is the mapping itself. A OneToMany association describes a relationship in the database, not a transactional boundary. The fact that a customer has orders does not mean the customer's aggregate must contain them. The guide is the invariant that must hold after every commit, not the shape of the schema.
21.05 Anti-pattern: a database shared across Bounded Contexts#
A shared database is one of the most serious strategic anti-patterns. Different contexts share the same tables or reach directly into another context's data. At first it looks pragmatic, but the tight coupling later blocks independent development and deployment.
Telltale sign. Go through the migrations of one context and look for a table that belongs to another team. The second symptom is operational: context A cannot be deployed without coordinating with the team of context B, even though their code never meets.
Where the rule stops. The mistake is not a single database instance, but a shared schema and a query that crosses the boundary. A modular monolith commonly runs on one database in which each module has its own schema and its own tables. A Shared Kernel with an agreed owner, a read-only replica for reporting, or an analytical context that reads data outside the domain model are not mistakes either. The anti-pattern starts the moment one context reads another context's write model and relies on its shape.
The synchronous HTTP adapter from the example above is not the only option, and for a modular monolith it tends to be the most expensive one. Three paths are worth considering, and each has its price.
Calls through an in-process interface. Context B exposes a port, and context A calls it directly, without a network. The boundary stays intact and no latency is added. The price is a shared deployment and the discipline to keep the port from becoming a passage into the other model.
Synchronous HTTP or gRPC. A necessity as soon as the contexts run separately. You pay with latency, with upstream outages that spill into your own operation, and with extra work on timeouts and fallback behavior.
Asynchronous replication via events. Billing listens to the CustomerBillingDataUpdated event and keeps a local copy of the data it needs (read model projection). The synchronous dependency disappears, and reads have the lowest latency of all three variants. The price is eventual consistency and code to backfill data for a consumer that joins later. Reliable publishing is handled by the Outbox Pattern.
A domain event describes a fact that happened in the past. That is why Evans describes it as ordinarily immutable[6]. The “ordinarily” is well placed: adding metadata when the message is published is common, while changing the amount in OrderPlaced is a conceptual contradiction. An event that can be overwritten after creation loses its value as a historical record.
Mutable events also do practical harm: in Event Sourcing, in audit logs, and between Bounded Contexts, where the receiving context counts on data that will not change anymore.
Telltale sign. Open the event class and look for a setter or a \DateTime without Immutable. Either one means the past can be rewritten in this system.
In practice, events work with two timestamps. occurredAt says when the thing happened in the domain; recordedAt says when the system wrote it down. For an event created by a user action, the two values coincide; for an import of historical data or a retroactive cancellation, they can be weeks apart. A single timestamp generated in the constructor is not enough for such a case.
Immutability of the instance does not solve schema versioning, though. As soon as an event outlives a deployment that adds a field to it, you need upcasting or a versioned type name; both are covered in Event Sourcing.
A related anti-pattern: the event as an application hook. Names like CacheShouldBeInvalidated or EmailNeedsToBeSent do not describe a fact; they are a command dressed up as an event. Verraes sorts messages into commands, queries, and information [8]; such a name confuses the first category with the third. A domain event says what happened in the domain and does not care who reacts to it. Once its name contains an instruction for the infrastructure, it is a command, not an event.
21.07 Anti-pattern: domain logic in the infrastructure layer#
The infrastructure layer (Doctrine repositories, Symfony Forms, controllers, event listeners) should be thin and delegate all domain logic to the domain. A domain rule in an infrastructure class breaks the layer boundaries and hides where no test will find it.
Telltale sign. Open any class in the Infrastructure/ directory and look for a condition that asks about domain state. The line if ($user->getStatus() !== 'pending') in a repository is a rule, not persistence.
The handler dispatches domain events straight to MessageBusInterface. This is where a boundary runs that is easy to overlook. It is formed not by the bus but by the event class and its contract. The book sends domain and integration events over a single event.bus. A domain event is an internal matter of the context, while an integration event is a public contract toward the outside. When another context hooks a handler directly onto a domain event, the event's shape becomes a public API that can no longer change. Separating the two kinds of events and publishing them reliably to the outside is covered in Outbox Pattern.
Layer boundaries can also be enforced by a tool, not only by agreement in code review. deptrac[9] and PHPArkitect [10] read the static structure of the code and stop a CI build that violates it. A useful minimum is a single rule: App\*\Domain must not reference Symfony\* or the Doctrine runtime (EntityManager, QueryBuilder). The rule has deliberate exceptions. The domain needs Symfony\Component\Uid for Uuid::v7() in identifiers. The book allows the Doctrine\ORM\Mapping attributes and Doctrine\Common\Collections in the domain (see Mapping choice: attributes as the default approach). If the rule also guards dependencies between contexts, it additionally lets through the identifiers of other contexts (App\*\Domain\ValueObject\*Id), because aggregates refer to each other by ID. One line of configuration replaces the same discussion repeated on every pull request. Watch out for the package name: the original qossmic/deptrac has been abandoned in favor of deptrac/deptrac.
21.08 Anti-pattern: over-engineering in simple applications#
The anti-pattern here is not DDD itself, but its ceremony without a complex domain. Aggregates, value objects, and domain events wrap plain database rows that a form and a table would handle.
Telltale sign. A trivial change passes through dozens of files in every layer, and the team spends more time on architecture than on the features the business needs.
The less costly path starts with a minimal approach and adds DDD elements only once domain complexity actually shows up. The full decision framework is in When Not to Use DDD: seven situations in which to skip DDD, the alternatives to it, and a decision tree.
Where the rule stops. Ceremony in itself is not a mistake. In a Core Subdomain, it is an investment that pays back with every change of the rules. The mistake is the same ceremony in a Supporting Subdomain, where nothing changes in a year except the VAT rate.
21.09 Anti-pattern: ignoring the Ubiquitous Language#
When the Ubiquitous Language is ignored, the same domain entity carries different names in different places. The language shared with domain experts stops applying, and developers spend more time translating between layers than modeling. Misunderstandings and bugs follow, and the code stops telling you anything about the domain.
Telltale sign. Have a domain expert describe one ordinary case and note every word you cannot find in the code, or that means something else there. The length of the list measures the drift.
None of these anti-patterns comes from not knowing the patterns; they come from convenience. Each one saves work in a given week, and the bill arrives a year later. That is why knowing the telltale sign is more useful than knowing the definition.
Vaughn Vernon covers the anemic domain model at length in Implementing Domain-Driven Design (2013), which is also the source of the two-question test from the opening of section 21.02. Further titles are listed in Resources.
Frequently asked questions
What is an anemic domain model, and how do you recognize it?
At first glance, an anemic model looks like DDD. It contains classes named after aggregates, entities, and value objects. All the logic, however, has been moved into services. The typical signs are getters and setters as the only methods, and classes without a single rule inside. Domain logic ends up in “Service” classes that manipulate the data from outside. The result is procedural code wrapped in object facades. A detailed analysis is in the Anti-pattern: anemic domain model section.
Is the anemic model always a mistake?
No. In his article on the anemic model, Fowler himself writes that a domain model is not always the best tool, and he points to Transaction Script. In a domain with only a handful of rules, one procedure per use case reads better than a layer of classes around it. The anemic model is a mistake when you pay the price of a domain model (mapping, wrapping values, splitting into layers) and get no benefit for it. Both sides of the argument are discussed in the When the anemic model is not a mistake section.
Why is Primitive Obsession a problem?
Primitive Obsession means using primitive types (string, int, float) where a domain concept belongs. Instead of an Email type, a string is passed around; instead of Money, a float and string pair. As a result, validation and rules are repeated at every call site, or they are forgotten. A value object with a single place of validation removes these duplicates, and the type gives context about what the value represents. Analysis and examples are in the Anti-pattern: Primitive Obsession section.
How do you tell that an aggregate is too large?
A God Aggregate typically shows three symptoms. The aggregate contains dozens of inner entities. Loading it hydrates thousands of rows into memory, even when the operation does not need them. Or concurrent operations on different parts silently break an invariant, because the root version does not catch the change in a collection. If two methods of an aggregate deal with mutually independent rules and share no invariant, they are probably two separate aggregates. The aggregate boundary should follow the boundary of transactional consistency – nothing more. A practical refactoring example is in the Anti-pattern: oversized aggregate (God Aggregate) section.
Why is a shared database between Bounded Contexts a problem?
A shared database formally keeps the data together, but in fact it erases the boundaries between Bounded Contexts. A schema change in one context can break another, concepts get mixed, and one team's model starts to depend on another's. The right solution is for each Bounded Context to own its data and for communication to go through a defined interface (an API, events), not through a shared table. A detailed analysis is in the Anti-pattern: a database shared across Bounded Contexts section.
Does a domain event have to be immutable?
Yes, as far as its content goes; adding technical metadata at publication is common. A domain event describes something that has already happened: OrderPlaced, PaymentSucceeded. And the past cannot be changed. An event without setters, with immutable attributes and a timestamp created at construction, is safe to share between handlers, persist in an event store, and use for reconstructing state after the fact. A mutable event leads to race conditions, nondeterministic processing, and an inconsistent audit trail. See the Anti-pattern: mutable domain events section.