johnnietheblack
johnnietheblack

Reputation: 13310

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:

Some arguments for:

Provide a setter (and don't force an id in the constructor), or force an id in the constructor, and remove the setter?

Upvotes: 5

Views: 490

Answers (2)

lcardosobr
lcardosobr

Reputation: 101

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

Upvotes: 1

eulerfx
eulerfx

Reputation: 37709

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.

Upvotes: 3

Related Questions