johnnietheblack
johnnietheblack

Reputation: 13330

How to handle required properties for Domain Entities?

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?

Option 2. Allow Id in the constructor to be null, but not provide a Setter

Option 3. Do I not worry so much, and provide a setter for it?

Upvotes: 0

Views: 168

Answers (1)

Oded
Oded

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

Related Questions