Difference between Value Object pattern and Data Transfer pattern

suri picture suri · Aug 8, 2011 · Viewed 18.4k times · Source

In which scenario can I use those design patterns in n-tier architecture?

Answer

Dmitry picture Dmitry · Aug 8, 2011

DTO is the object that you can use at the boundaries of the system. When you have a SOAP web service for example and you want to return response you would use DTO. It easier to deal with than actual XML that has to be returned over the wire. DTOs are often generated by tools, based on WSDL for example. DTO are often tailored to the needs of service consumer and can be affected by performance requirements.

Value objects on the other hand live in the core of the system. It captures pieces of business logic and maybe formatting rules. It makes your code more type safe and expressive. It also tackles "Primitive obsession" anti pattern. Good example is using class "SocialSecurityNumber" instead of string. Or Money instead of decimal. These objects should be immutable so that they look more like primitives and can be easily shared among different threads.

For example in hypothetical 'customer-order' system:

CustomerAndLastFiveOrders is DTO (optimized to avoid multiple network calls)

Customer is Entity

Money and SKU are Value objects