Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity's id as constructor argument or through a setter method?

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 id but different properties. (if I pulled 3 different Users from the db and set their id values to the same)

Some arguments for:

  • if I don't HAVE to instantiate the UserEntity with an 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?

like image 967
johnnietheblack Avatar asked Oct 09 '22 07:10

johnnietheblack


2 Answers

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.

like image 169
eulerfx Avatar answered Oct 13 '22 11:10

eulerfx


@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.

like image 1
lcardosobr Avatar answered Oct 13 '22 11:10

lcardosobr