Can a DTO have instance methods returning derived values?
Asked Answered
L

1

9

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?

Laura answered 12/2, 2010 at 22:2 Comment(1)
good question, I was just about to ask!Anzio
P
14

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.

Peloquin answered 12/2, 2010 at 22:5 Comment(6)
Most best practices books I have looked at as of the past year have advised against the DTO.Facies
The question was specificaly about the DTO pattern not whether it should be used or not. The problem with the DTO is it is misapplied in a lot of situations e.g. where there is no process boundry! That the reason it came around, aggregating data from a remote process to save costly round trips.Peloquin
Should I use @override compareTo in a DTO or is not recommended? Is better to use a wrapper for that purpose?Jovanjove
@Facies care to explain why DTOs are bad? which reliable book are you talking about?Retake
And instead of stters, could I have methods to set the properties?Depart
What about static projection methods? Is it not better to group these into the DTO than to have them scattered about the codebase?Teasel

© 2022 - 2024 — McMap. All rights reserved.