Reputation: 9194
I have a scenario where I am starting with an Order Message. Over time the message could be modified (into different versions). What would be a good approach to see what version the message is and pass it to the appropriate processing mechanism? I could look at the version (Will always have a header with version info, etc) and then use a case to send it to the proper parser (Currently using LINQ to XML). However, that doesn't seem very elegant. Especially if we have like 10 versions we need to support.
Nothing pops out to me...just wanted to see how others would approach this.
Upvotes: 0
Views: 704
Reputation: 970
An alternative solution is to use a set of xslt scripts which would transform the old version of the xml to a newest one (by sequential applying scripts for transforming version N-1 to version N). In this case, you would have just one "processing mechanism" which only will support the newest version of XML.
The processing mechanism would look as follows:
Upvotes: 1
Reputation: 59131
If you have X versions of the schema, you'll need X code paths to handle them.
To pick your implementation you're going to have to have a switch statement somewhere. That switch could simply call methods, or it could be in a factory method that returns the correct parser (class or delegate).
This doesn't preclude you from sharing parts of your code between versions, and it is a good idea to break down your parsing into its component parts in order to support this. You can break them down via classes or via methods.
You could have a common base interface to kick off parsing any version, and get back the object graph that the XML represents. The resulting object model should ideally be as version independent as possible so you can share common functionality.
Alternately you could use XSLT to upgrade the data, and use only one parser.
You can either implement this once for each version and chain all the transforms, or you can transform directly to the latest version and modify previous version's transforms with every release.
Chaining transforms has better maintenance cost. Direct transform has better perf.
You'll still need a switch for this :)
Upvotes: 1
Reputation: 8362
If your version is a number, you could have something like public interface IOrderMessageHandler { void Handle( OrderMessage message ); }
public class OrderMessageHandlerVersion123 : IOrderMessageHandler { ... }
having a naming convention and constructing them using reflection:
var handler = (IOrderMessageHandler)Activator.CreateInstance( GetType().Assembly.GetType("MyNamespace.OrderMessageHandlerVersion" + message.Version));
handler.Handle(message)
Upvotes: 1