Best OO practice for adapting one type to another?

I have a set of domain objects that I need to convert to a different type for use in the .NET framework. What is the best practice for such a conversion?

Specifically, I have a type called ContentEntry and I need to convert it to a SyndicationItem for use in creating a SyndicationFeed. The conversion itself is straight forward, but I'm looking for a good pattern. Create a ContentEntry method named CreateSyndicationItem () or maybe a separate converter object? An extension method perhaps?

This will be somewhat subjective, but I'll be grateful for some ideas.

Edit Note. I would like to point out that I have no control over the SyndicationItem. It is built into the .NET Framework. Also, I'd really like to convert multiple ContentEntry to SyndicationItems in one go.

+1


source to share


5 answers


As the constructors of SyndicationItem cannot be changed, I suggest you use the factory pattern . Create a SyndicationItemFactory class that has a CreateSyndicationItem () method. This method returns a SyndicationItem object. In this case, you only need one version of the method, which will accept a ContentEntry object.



When you say that you want to create multiple ContentEntry objects at once, I assume that you said an array of ContentEntry objects. Another method (for example, CreateSyndicationItems ()) can return an array of SyndicationItems and take an array of ContentEntry objects as a parameter.

+3


source


I would suggest looking at Adapter Template



In computer programming, an adapter design pattern (often called a wrapper pattern or just a wrapper) translates one interface for a class into a compatible interface.

+4


source


IMHO, a converter class that converts one way and maybe another is what you should be doing. The class should have a single purpose, for example to represent a ContentEntry. Adding a transform gives it a second target and therefore violates this OO rule.

+1


source


It depends ... do you just want a convenient way to host the transform method? If you are in control of one or both classes, you can simply add an overload of the throw operator so that you can simply pass one class to the other. If you want to make it obvious, you can make the explicit statement

SyndicationItem item = (SyndicationItem)entry

0


source


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

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

Reasoning:

  • You don't want any object to have a relationship with another object.
  • The conversion process itself has no state to control after it completes (good for a static method)
0


source







All Articles