This building block is the opposite of the Entity. Why?
- it’s totally immutable, so it doesn’t change overtime
- it’s the value it holds which is significant, not the identifier which doesn’t exist in this case
Value Object (VO) is not only a container for some data, it may also realise some business logic. Let me show you the most overused example out there (but a good one) which is Money representation. It usually contains two values - amount of money and its currency, which is also the Value Object.
Meaningful Value
This is the first great advantage, the person who will read your code will be given clear information about the purpose of this particular object. No more guessing what type of number you have to deal with, no second variable representing currency, no mess in the code. From now on everything is wrapped in nice and clean interface, giving you fewer headaches.
Business Logic
Have you ever dealt with floating-point arithmetics in binary system? I’m sure you did so you know the pain. Thanks to the Money object, performing arithmetic operations is a piece of cake. Calculate an interest in banking system? Applying 8,5% promotion to product in cart? Bring it on!
Always Valid
Another great perk is the “validation during creation”. In both Money and Currency you perform checks if primitive values passed to their constructors are logical. You cannot pay -2 with non-existing currency, right? In this case VO will not be even created, so some invalid data has no slightest chance to go wild.
No Setters
Setters and immutability? It doesn’t make sense!
Comparing Value Objects
Two Value Objects are identical when they hold the same value. Here, not only the amount must be identical but the currency as well. And what about things like the address, there are at least four properties. They simply have to be compared one by one.
Example
As I said before, Money object consist of two values: amount of money and its currency, so it will be represented by two Value Objects.
And the king himself, using already validated Currency.
Summary
What do you say? Someone had an excellent idea inventing such a useful type of object, don’t you think? Stay with me and you will see how perfectly it copes with other building blocks.