I have to add new funcionality in a web service legacy project and I’m thinking what is the best approach for a concrete situation.
The web service is simple: It receives a XML file, unmarshalling, generates response’s objects, marshalling and finally it sends the response as a XML file. For every XML files received, the web service always responds with the same XML structure.
What I have to do is to generate a different XML file according to the XML received. So I have a controller class which has all marshalling/unmarshalling operations, but this controller class has to be an instance. Depending on XML received I need some marshalling methods or others.
Trying to make few changes on legacy source, what is the best approach? My first approach was to do a factory method pattern with the controller class, but this class has to be an instance.
I want to keep, as far as it goes, this structure:
classController.doMarshalling();
I think this one is a bit smelly:
if(XMLReceived.isTypeOne())
classController.doMarshallingOne();
else if(XMLReceived.isTypeTwo())
classController.doMarshallingTwo();
else if(XMLReceived.isTypeThree())
classController.doMarshallingThree();
else if ...
I hope my question is well understood
2
This is a common problem, mapping input to a class that can process it. One common solution is to build a map from the input type to the processing class. To handle input, you determine the input type, use the map to look up the processing class, then instantiate the class and call the desired methods.
In Ruby:
processorByType = { 'type1' => Type1Processor,
'type2' => Type2Processor,
...
}
def handle(input)
processorByType[input.type].new().process(input, context);
end
2
Is this not a classic case for generics?
try
{
ClassController<typeof(XmlReceived)>.DoMarshalling();
// OR...
ClassController.DoMarshalling<typeof(XmlReceived)>();
}
catch (...)
{
... handle if XmlReceived is not a supported type
}
You could use the Strategy pattern. It does exactly what you want, it executes different algorithms for different scenarios which are often related. The wikipedia article gives an example implementation for java.