I have a Value Objects - Money and ExchangeRatio. I want to convert one Money to another using ExchangeRatio. So is it good to build a convert behavior on Value Object ExchangeRatio like so:
ExchangeRatio.Convert(Money) returns Money.
Or should I delegate it to some Domain Service instead? In other words can I build a behaviour on Value Object that doesnt change its state but has some logic, mathematic or other different object creation(based on its state) in it?
Being immutable, Value Objects cannot be changed once they are created. Modifying one is conceptually the same as discarding the old one and creating a new one. Frequently, the Value Object can define helper methods (or extensions methods) that assist with such operations. The built-in string object in the .
Yes, you can have value objects inside other value objects. I think the simplest example of this would be the class Money, which contains an amount and a Currency, which is another VO.
Value objects are not only containers of data - they can also contain business logic. The fact that the value objects are also immutable makes the business operations both thread-safe and side-effect free.
In computer science, a value object is a small object that represents a simple entity whose equality is not based on identity: i.e. two value objects are equal when they have the same value, not necessarily being the same object. Examples of value objects are objects representing an amount of money or a date range.
What you are doing sounds perfectly reasonable to me. Eric Evans uses an example of a Paint
object in his book that does the same thing. The mixIn
method takes another Paint
object as input and returns a new Paint
object.
With the Paint
sample he demonstrates side-effect free functions in the book.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With