问题
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