Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a DTO have instance methods returning derived values?

Is it ever acceptable for a DTO to have instance methods which return derived values based on the DTO's data? Or should DTOs be pure data containers with no additional methods (other than getters/setters)?

The purist in me says that it is far to easy for business logic to creep into such methods. However, if (for example) a DTO is shared across application layers, then maybe there is an argument for having such methods on the DTO.

What are your views on this? Are there ever situations where it is acceptable, or should this sort of thing be avoided? And why/why not?

like image 608
KarstenF Avatar asked Feb 12 '10 22:02

KarstenF


People also ask

Can DTO objects have methods?

Data Transfer Objects are public (static) classes with no methods, other than the compiler supplied default constructor, having only public fields limited to the easily serializable types: i.e. A DTO is equivalent to a struct in C.

What should a DTO contain?

DTOs normally are created as POJOs. They are flat data structures that contain no business logic. They only contain storage, accessors and eventually methods related to serialization or parsing.

Can DTO have Behaviour?

The difference between data transfer objects and business objects or data access objects is that a DTO does not have any behavior except for storage, retrieval, serialization and deserialization of its own data (mutators, accessors, parsers and serializers).

Can DTO have logic?

DTOs do NOT contain logic. DTOs are often used with a form of data mapper called a DTO assembler. A record set is a collection of DTOs.


1 Answers

DTOs should not have behaviour, they are mere containers for transporting data across process boundries and should consist of setters/getters only.

It should be avoided at all costs otherwise it would be construed as misapplication of the DTO pattern.

like image 181
David Avatar answered Nov 06 '22 12:11

David