I was thinking about some entities I need, when I came across a very interesting concept: Immutable Objects.
The Immutable Objects are very handy to manage the so called Value Objects.
In the Domain Driven Design (DDD) properties of an Entity
can have two different values: other Entities (Order->getProduct()
– here Product
is an Entity
and its properties can change) or simple values (Product->getPrice()
).
Price
, in our example, is a simple value, not conceptually an Entity
. Until now, it probably is a simple property in your Entities (as it was in mine!).
But, in this second case, the Value Objects play their parts: they represent those values in an immutable state.
In fact, if you reflect about the data Price
, you realize that a Price
is something like “100 Eur”. If you put your attention on the value, you can recognize more than one smaller parts in it: a numeric value – 100 – and a string value – Eur.
A Price
is a Price
only if we indicate both the numeric part of it (100) and the string part of it (Eur): If we indicate only one of the two, it is not a Price
because we don’t know how much money does it represents or in which currency the price is expressed.
So we need both the “amount” and the “currency” to have a real value. Think it as a “composite value”.
And the important thing to consider to understand what Immutable stands for: if in the Price
we change the amount, we have a different price. If in the Price
we change the currency, we have, again, a different price.
But if in a Product
we change the Price
, we don’t have a different Product
but the same one with only a different Price
.