When you have an entity, such as UserEntity, who's id
property is derived from its primary key in the db - should you provide a setter method such as setId()
?
Some arguments against:
id
but different properties. (if I pulled 3 different Users from the db and set their id
values to the same)Some arguments for:
id
in the constructor (since it has a setter method), I can use the methods of the UserEntity object with temporary / fake / new user values...without having to persist it first.Provide a setter (and don't force an id
in the constructor), or force an id
in the constructor, and remove the setter?
The identity value of an entity should be managed by the persistence layer and ideally would not be settable by anything else - the persistence layer should assign a new identity value upon persistence and set it upon retrieval. Furthermore, you should be able to use a transient (not persisted) entity without needing access to its identity. Allowing the identity to be set through the constructor can lead to issues because there is no authoritative source for identity values. One example where identities can be assigned from external sources is if a client requests that a newly persistence entity has a UUID as it's identity, though this example is contrived.
@johnnietheblack, i prefer create a private setter and a public getter to entities' ids. Validations will be there into the setter (if necessary) and I set this id exclusively into constructors. Numeric ids are instantiated with zero values helping me to track theirs lifecycle.
Domain Driven Design by Eric Evans talk about model domains when Patterns of Enterprise Application Architecture by Martin Fowler deep into infrastructure of this applications. I believe that they are complementaries and I recommend.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With