What Is A Domain Entity?
While Data Transfer Objects, or DTOs, are simplistic containers for shuttling data between various layers of our software architecture, Domain Entities, or simply Entities, are something different altogether.
A Domain Entity is a refined and sophisticated thing—it’s an object modelling a concept in our business or problem domain. Entities should possess well-defined behaviour operating on internal data or state.
For example, when you do your online groceries shopping, there exists a concept of a shopping cart that remembers the items you want to purchase. It is likely that your supermarket’s eCommerce website models this behaviour via a shopping cart entity. As you select quantities of grocery product via the GUI for your weekly shop, an instance of a shopping cart entity will keep track of your groceries. It will also recalculate the total cost of everything in the cart.
A well-designed shopping cart entity should be a pretty good software imitation for the operation of a physical shopping cart. Since actual metal shopping carts at your supermarket do not calculate the total cost for all the items in the cart, a domain entity model is even more capable!
Such a software shopping cart entity keeps track of state—the quantity & product combinations in the cart (e.g. 1 block of cheese, 4 bagels, etc.). This internal state will be protected—i.e. encapsulated—and can only be manipulated via carefully designed public methods. We want the data inside the entity to be shielded from ad-hoc external modification to ensure its ongoing consistency.
In short, domain entities are objects containing protected data that can only be manipulated via public methods enforcing a set of business rules.
Domain entities protect their internal state from inadvertent access the way a mama grizzly bear protects its cub—you don’t get to go near it, not directly anyway.
Let’s compare notes on DTOs and Domain Entities:
- DTOs are bags of data without behaviour; they do not protect their state.
- Entities are modelling problem domain concepts; they have behaviour to read and modify encapsulated data.
What about entities that encapsulate business rules in their behaviour but do not need to remember any internal state? Welcome to the world of Domain Services. We’ll take a closer look at these next week.