Wednesday, April 25, 2012

Usage of Chain Of Responsibility in a practical application

Recently I have come across a situation where I had to process a collection of incoming XML files and run some logic according to the content of each and every XML message. At my office we are using file based electronic data interchange. Yes, I know that file based electronic data interchange may be somewhat an old timers approach , but still there are situations that you got to use it. Without stepping into any arguments , I just wanted to show you how this could be achieved using Chain Of Responsibility pattern.

There are few different operations that were needed on the incoming set of messages. Validation , Filtering , Sorting , Mapping and Aggregation. While these are the currently needed operations , in future we may have more and more different types of processing.

  • Validation : The set of the XML messages must be validated for a given set of rules. The rules are coming from a data base and those would be configurable depending on the requirement. The rules are configured based on the type of the message. Ex : if the property "message type" of an incoming XML message is "Sales Order" , then "project name" must not be empty
  • Filtering : The set of the XML messages must be filtered for a given set of rules. The rules are coming from a data base and those would be configurable depending on the requirement. The rules are configured based on the type of the message. Ex: if the XML message file name starts with "TMP_" , then filter all those messages
  • Sorting : Sorting happens based on the message content of each XML message. Ex: sort all the order items in a given XML message based on the order sequence number
  • Mapping & Aggregation : There operations are also done at each message level
When looking at each operation above , we could take each of those operations into individual classes and chain those classes according to requirement. Sometime you may want to execute Filtering first and Validation second or other way around. Sometimes you may want to turn off one operation , let's say Mapping and just go with the other operations. Later on there may be a new requirement for a completely new operation type on all the messages etc.. By considering all these it is better to have these operations separated into independent classes and combining them configurable.

Below is a possible high level design for this,

Below are some of the class diagrams , and sequence diagrams which may realize the above high level design.
VALIDATION
AGGREGATION
MAPPING

Going Technical , Prototype pattern

Well this is the year of 2014 and I have not made a single post yet for this year. Frankly I did not have a good real life example for expla...