tags:

views:

227

answers:

5

I have a collection of domain objects that I need to convert into another type for use by the .NET framework. What is the best practice for doing such a transformation?

Specifically, I have a type called ContentEntry and I need to convert it into a SyndicationItem for use in putting into a SyndicationFeed. The conversion itself is straight forward but I'm looking for a good pattern. Do I create a method on ContentEntry called CreateSyndicationItem() or perhaps a separate converter object? Perhaps an extension method?

This will be somewhat subjective, but I'd appreciate some ideas.

Edit Note: I'd like to note that I don't control SyndicationItem. It is built into the .NET Framework. Also, I'd really like to convert several ContentEntry objects into SyndicationItems at one time.

+1  A: 

IMHO, a Converter class that converts one way and possibly the other is what you should do. A class should have one purpose, for example represent ContentEntry. Adding conversion gives it a second purpose and therefore breaks that OO 'rule'.

Rob Prouse
+4  A: 

I'd suggest looking at Adapter Pattern

In computer programming, the adapter design pattern (often referred to as the wrapper pattern or simply a wrapper) translates one interface for a class into a compatible interface.

Brabster
A: 

It depends ... do you just want a convenient way of hosting the conversion method? If you control one or both classes, you could simply add a cast operator overload so you can just cast one class to the other. If you want it to be obvious, you can make an explicit operator

SyndicationItem item = (SyndicationItem)entry

Joel Martinez
A: 

If you can do the conversion through the public contract of both types, I highly recommend an extension method.

See also, System.Linq.Enumerable.ToList(), Enumerable.ToDictionary()

Reasoning:

  • You don't want either object to have coupling with the other object.
  • The conversion process itself has no state to manage once it has been completed (suitable for static method)
David B
+1  A: 

As as cannot modify the SyndicationItem's constructors, I'd suggest you use the factory pattern. Create a SyndicationItemFactory class that has the method CreateSyndicationItem(). This method returns a SyndicationItem object. In this case, you'll only need one version of the method, that will take a ContentEntry object.

When you say you'd like to create multiple ContentEntry objects at once, I'm assuming you have say an array of ContentEntry objects. Another method (say CreateSyndicationItems()) might return an array of SyndicationItems, and take an array of ContentEntry objects as its parameter.

David Arno
In my situation here, I've found this to be the best method. Casting doesn't seem appropriate, and since no state needs to be maintained, creating a new converter class that gets instanced every time I need to make a conversion seems overkill. My factory currently has only static members.
Brian Vallelunga