Entity states

Today I would like to discuss domain entity states.

The other day I saw a video and an article in the blog of one interesting software developer. And in this article, he writes exactly what I talked about in my previous post, about the separation of entity and its state. Yes, in slightly different words, but he gives the same arguments for separation. And now I want to talk a little more about states and their storage.

It is quite obvious, as I noted earlier, that when saving entities, of course, we are talking about saving their states. In general, it is not correct to talk about saving entities, since an entity is about behavior, and it is stored in your application code, but not in the database. And because of that, all this confusion arises with the ORM and, in particular, with the Entity Framework, which tries to implicitly allocate the state of an entity for saving, which causes difficulties in non-trivial cases. It would be much more convenient to explicitly separate the state of an entity as a separate class in advance.

Separate entity state

If you look at the state of an entity as a separate element of the program, then it will be 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, and when constructing an entity, it would be logical to use a constructor that takes an object of this class as a parameter.

So, what gives us the state of the entity in the form of a separate class:

  1. State is easily serialized and easily persisted by various ORMs. At the same time, public access to all its fields does not violate encapsulation.
  2. Moments of state change are clearly visible in the code. No matter how hard we try to hide the fact that the state of entities needs to be saved, it still happens, and it’s good when you can clearly see the moments of its change and saving.
  3. The serialized state can be stored not only in the database… But I going to write about this in one of the following posts.

Leave a Reply

Your email address will not be published. Required fields are marked *