Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Value Object have behaviour?

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?

like image 267
Radek Avatar asked Feb 26 '15 20:02

Radek


People also ask

Can value objects have methods?

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 .

Can value object have value object?

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.

Can value object have logic?

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.

Can objects be values?

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.


1 Answers

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.

like image 187
Eben Roux Avatar answered Oct 14 '22 06:10

Eben Roux