views:

94

answers:

1

I'm building a REST API that exposes data as XML. I've got a whole bunch of domain classes in my domain layer that are intended for consumption by both the service layer behind the API, and the client API that we will be providing to customers. (Customers do have the option of interacting directly with the REST API, but the client API simplifies things). I want to keep my domain classes clean of any data persistence logic, but I'm strugling with trying to figure out if it's OK for the domain classes to implement IXmlSerializable to help simplify the process of serializing the data that is exposed through and retrieved from the API. I started out thinking that I'd keep the domain classes free of any serialization logic and instead decorate them with serialization behaviors, e.g. wrap the domain object inside of an object that handles the serialization. Am I making things more complicated than they need to be? Any thoughts on how I should approach this? Thanks!

+3  A: 

Domain classes should be concerned with business logic only, not with persistence or serialization.

You should create a set of Data Transfer Object (DTO) classes, each corresponding to one of the domain classes. These classes would only contain the properties, from the domain classes, that you have decided to expose. This permits the domain classes to have properties which are not exposed through your persistence or serialization layers.

Only the DTO objects would be serialized and deserialized.

You may then find it convenient to create static "translate" methods to translate between the domain and DTO objects.

John Saunders
What would your serialization layer look like? Would you have methods that take in DTOs and output them in XML? Or would you take a stream and serialize to it?
cs
It depends on what I need. I would tend to follow the pattern of many XML-based APIs in .NET, and accept an `XmlWriter` as the destination. If I found the calling code repeatedly creating the `XmlWriter` from a stream, I'd add an overload that takes a stream. If I found the calling code using `XPathNavigator.AppendChild` to create the `XmlWriter`, then I'd write an overload that accepts `IXmlNavigable`, etc.
John Saunders
Thanks, John, I appreciate it.
cs
This concept sounds great - would it be easiest to have both the domain object and its corresponding DTO implement the same property-only interfaces and the constructor of the DTO take in an instance of that interface (the instance being a domain object instance)?
Jesse C. Slicer
I don't see the value of using a property-only interface here. It won't save you any code, as far as I can see.
John Saunders