Is is ever appropriate to put functionality in a DTO?
Is it ever appropriate to put functionality other t开发者_高级运维han basic setters and getters in a DTO?
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.
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.
精彩评论