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:
- opens the door to possible accidental overwrites of other UserEntities in the db
- two (or more) UserEntities could exist at any time with the same
idbut different properties. (if I pulled 3 different Users from the db and set theiridvalues to the same)
Some arguments for:
- if I don’t HAVE to instantiate the UserEntity with an
idin 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.