Reputation: 678
I am constructing an application which will be able to output data to RSS format and also a more detailed custom XML format. I am having two conflicting approaches to how I would create the object heirarchy.
Option 1 - Build the hierarchy according to what is required by each format (RSS/XML)
FeedItem (RSS properties)
title
description
link
^
|
DetailedFeedItem (Detailed XML properties)
expirationDate
^
|
Article (Detailed XML Article-specific properties)
paragraphs
Although this solution works, it feels like the objects are coupled to their visual requirements (RSS/XML).
Option 2 - Build the hierarchy based on a more general abstraction:
Item
title
description
expirationDate
^
|
Article
paragraphs
This approach seems more flexible and simple to me, but then when I am constructing the RSS, I may have properties that will not be populated (expirationDate, paragraphs). If I go with option 2 I was thinking of creating a class such as RSSMapper which would take an object and map only the necessary properties to the RSS format - e.g., RSSMapper.mapArticle(Article article).
What do you think would be the best way forward?
Upvotes: 0
Views: 90
Reputation: 2972
You are right with option 2) (which is basically an Adaptor Pattern).
Your domain object should be somehow independent from the usage of it. Using a mapping (or adaptor) class to convert the model into a View is the best way to ensure encapsulation and separation of responsibilties. This way, if you want to expose the model in another third format (e.g. HTML?) you just need to create the relevant adaptor without having to change any of the existing code.
Upvotes: 1