I have two instances in an application where I need to implement functionality to convert an object from one type to another. One to go from a domain object to another domain object, another to go from a domain object an XmlDocument.
The way I have initially set it up is to include a ToXml() and ToMyOtherDO() within DomainObject1 and DomainObject2 respectively.
The functionality in ToXml isn’t really specific to the implementation of DomainObject1 and could probably live anywhere. ToMyOtherDO() has functionality very specific to the type it lives in. Both perform type conversions but are quite different.
My question is, have I placed this functionality in the correct place? Would this functionality be better placed in a helper class? Or some place else – perhaps overriding the explicit casting operator?
I usually like to put this kind of functionality in extension methods.
EDIT: Explanation
I generally prefer to put this kind of functionality in extension methods because I don’t feel that the class that needs to be “converted” really needs to know how to do the conversion. This provides some decoupling. You can easily change the format of your XML without changing the object that you are converting to XML (especially useful when the object to be converted is in a seperate assembly).
You will eventually run into a situation where you want to convert your domain object to something that it does not really need to know about. For example, maybe you want to convert your domain object to a Json.NET
JObject. The assembly containing your domain object wouldn’t need a reference to the Json.NET library if you used extension methods to handle the conversion in a separate assembly.The extension methods are great especially when dealing with the Entity Framework. The code for the entity classes are auto-generated, so you can’t just add a
ToXML()orToJObject()to the class.These are just my preferences, and I don’t always use extension methods to handle this kind of functionality. It’s just another great tool to have in your arsenal, for solving these kinds of problems.