Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DDD: Can immutable objects also be entities?

I've read countless posts on differences between Entities and Value objects and while I do think that at least conceptually I understand how the two differ, it appears that in some of these posts authors consider a particular domain concept to be a VO simply because it is immutable ( thus its state will never change, at least within that particular domain model ).

Do you agree that if the state of an object will never change within particular domain model, then this object should never be an entity? Why?

thank you

like image 583
bckpwrld Avatar asked Jan 15 '14 18:01

bckpwrld


People also ask

Are entities immutable?

Entity vs Value Object: immutability Value objects should be immutable in a sense that if we need to change such an object, we construct a new instance based on the existing object rather than changing it. On the contrary, entities are almost always mutable.

Can objects be entities?

An object having a specific identity and defined primarily by it is called an Entity. We model a domain concept as an Entity when its individuality is primordial and it must be distinguished from other objects in the system.

What is an immutable Entity?

Annotation Type Immutable An immutable entity may not be updated by the application. Updates to an immutable entity will be ignored, but no exception is thrown. @Immutable must be used on root entities only.

Can a value object contain an Entity?

Yes it can. This would be a relatively obscure case but DDD allows for it and it can be useful. From the DDD book by Eric Evans: VALUE OBJECTS can even reference ENTITIES.


2 Answers

The object could be an entity if you need to identify it. According to the DDD book, if an object has identity and lifecycle but will not change over time, you could also consider the object as an event.

like image 171
Yugang Zhou Avatar answered Oct 22 '22 22:10

Yugang Zhou


Do you agree that if the state of an object will never change within particular domain model, then this object should never be an entity? Why?

I'd say 90+% of entities will change at some point in their lifetime. But some entities might be unchangeable because of their nature in the domain - a PrepaidPhoneCard, a TransferOrder in a banking system for instance.

Some also like to make their Entities immutable by default because it helps shaping a design that preserves invariants and makes domain operations explicit : http://www.jefclaes.be/2013/04/designing-entities-immutability-first.html

like image 32
guillaume31 Avatar answered Oct 22 '22 23:10

guillaume31