views:

70

answers:

2

Is it ever appropriate to put functionality other than basic setters and getters in a DTO?

+1  A: 

Well, in a number of scenarios you may well need some serialization code (for whatever serialization interfaces your serializer API demands - things like IXmlSerializable / ISerializable in .NET), but I guess that isn't what you mean...

It really depends on the scenario. If you have an object model that is simple enough to allow you to use your domain model for serialization, then for small projects there may be little benefit in splitting it out - a separation of concerns issue? Probably. Going to cause long-term pain? Probably not (at least, not if you use a contract-based serializer, so you can swap it without anyone noticing).

For more complex models, you often will need a separate DTO model to the domain model - in which case you might need somewhere to put the conversion logic (methods / operators / etc) between domain and DTO - so that might live in there, but if you have got a separate DTO it is unlikely to have much additional logic - that logic belongs mainly in the domain model and the other business classes.

Marc Gravell
A: 

By definition a DTO does not have any behavior, except for its data accessors. If you need some logic in them is likely that you need some refactoring your model.

JuanZe
Say I take a `Candy` as a parameter for my ASP.net webmethod. Can't I add a `SaveToDb` method to him? What would be the best practice? Prefer Composition over Inheritance?
Alex Bagnolini