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?
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.
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.
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).
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.
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.
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