Reputation: 13330
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?
id
). id
to give it. Option 2. Allow Id in the constructor to be null, but not provide a Setter
id
, and give it back.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?
id
of a UserEntity, and overwriting a different UserEntity in the db.id
ahead of time, which I can pass to my Repository for saving.Upvotes: 0
Views: 168
Reputation: 499092
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).
Upvotes: 3