Today, I would like to discuss domain entity states.
Recently, I came across a video and an article on the blog of an interesting software developer. In this article, he discusses exactly what I covered in my previous post regarding the separation of an entity and its state. Although phrased differently, he presents the same arguments for separation. I would like to elaborate on states and their storage.
As noted earlier, saving entities essentially means saving their states. Generally, it is inaccurate to speak of saving entities, as an entity represents behavior stored in your application code, not the database. This leads to confusion with ORMs, particularly Entity Framework, which attempt to implicitly extract the entity’s state for persistence, causing difficulties in non-trivial cases. It is often more convenient to explicitly define the entity’s state as a separate class.
Separate Entity State
Viewing the entity’s state as a separate program element makes it a classic Data Transfer Object that allows you to transfer data from the domain model to the data storage subsystem. This class must contain a set of fields that represent the state of the entity. When constructing an entity, it is logical to use a constructor that takes an object of this class as a parameter.
What are the benefits of defining the entity state as a separate class?
- Easy Serialization: The state is easily serialized and persisted by various ORMs. At the same time, public access to all its fields does not violate encapsulation.
- Visibility of State Changes: State changes become clearly visible in the code. Regardless of attempts to abstract persistence, state must be saved. Explicitly seeing when changes and saves occur is beneficial.
- Flexible Storage: The serialized state can be stored in various mediums, not just the database. I will cover this in a future post.