Can Value Object have behaviour?
Asked Answered
Y

1

8

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?

Yenta answered 26/2, 2015 at 20:36 Comment(0)
A
4

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.

Abigailabigale answered 27/2, 2015 at 4:41 Comment(3)
Ok, becuase Paint only knows about Paint instances in his behaviour. Here ExchangeRatio knows about Money, so its different case.Yenta
I would put the convert method on the money object though as you are working with money, not with ExchangeRatio. Thus Money.ConvertTo(ExchangeRatio)Trillium
Well, Radek, further on the Paint is further refactored to include a Pigment. So the Paint knows about the pigment and uses a ratio internally. So as long as the closure of operations business holds we should be good. Anyway, as SneekyPeet has mentioned you could swop things around a bit as your example actually looks more like a domain service already ;) --- the answer still holds, though: you can have behaviour on your VO.Abigailabigale

© 2022 - 2024 — McMap. All rights reserved.