How to handle required properties for Domain Entities?

主宰稳场 提交于 2020-01-25 07:19:05

问题


I have a UserEntity that is eventually persisted in the DB according to it's id property. In this case, the id property is obviously sensitive, because changing it would cause the UserEntity to be saved over a different UserEntity when persisted later.

I would therefore like to help safe guard against something like this happening...

Option 1. Do I FORCE the id to be passed into the constructor, thereby removing the Setter?

  • This would mean that every UserEntity that the Repository is given to persist will be valid (because it has the minimum requirement of an id).
  • The downside is that my Controller wouldn't be able to create a new UserEntity() because it wouldn't have an id to give it.

Option 2. Allow Id in the constructor to be null, but not provide a Setter

  • This would essentially create two types of UserEntity objects: ones that have been persisted, and ones that haven't.
  • I could do new UserEntity() anywhere, fill it with it's values, then pass to the Repository who would then save it, create a new UserEntity with the new id, and give it back.
  • This is cool, but means I need to double check that my entity has an id anywhere that I want to use it for persisting / domain logic / etc, to make sure that it is a saved entity.

Option 3. Do I not worry so much, and provide a setter for it?

  • This exposes the risk of changing the id of a UserEntity, and overwriting a different UserEntity in the db.
  • On the upside, I can create a new UserEntity() without knowing the id ahead of time, which I can pass to my Repository for saving.

回答1:


If you care about the validity of your domain objects, you need to ensure validity in all times.

This means that you don't provide setters on properties that you do not want changed directly, but use specified methods to mutate their state.

If the id in your example never changes, you should only ever set it in the constructor (and enforce it being passed in).



来源:https://stackoverflow.com/questions/9741195/how-to-handle-required-properties-for-domain-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!