Best way/pattern to build request based on different service

I have a about 20 different services which I have to send requests to which require a slightly different set of headers.

The bad legacy code is something like this,

row = db.query_for_service()

if row.type == 'foo1'
   // add common headers to request
   // add foo1 specific headers 1
   // add foo1 specific header 2
   // add foo1 specific header 3
else if row.type == 'foo2'
   // add common headers to request
   // add foo2 specific header 1
...
...
...
else if row.type == foo20
   // add common headers to request
   // add foo20 specific header 1
   // add foo20 specific header 2 
   // ...

send_request()

What is the best way to refactor this? I have considered some patterns that may work here (strategy, builder) but I am not too sure.

I am currently learning both Java and Python and I would to get thoughts on how the solutions would differ in the two languages

Answers


Personally, what I would do is something along these lines.

#Put this in the initialisation 
Map foos<row.type,String> = new Map<row.type, String>()
#Populate the map 
map.set('a') = 'headerA specific params x=1'
map.set('b') = 'headerB specific params x=2'
map.set('c') = 'headerC specific params y=3'
map.set ...

Map bars<String,String> = new Map<String,String()
bars.set('fooA') = 'a,b'
bars.set('fooB') = 'a,c'
String commonheader = "HTTP/1.1"


#This would be in a method    
row = db.query_for_service()
String output_header += commonheader
for i in bars.get(fooN).split(','):
    output_header += foos.get(i)
send_request()

In sort of pseudo java/python. The map would be pre-filled with everything you need, then just pick out what you want and attach.


Need Your Help

Don't load xml data to list when publishing by Flash CS 5.5

actionscript-3 flash flash-cs5.5

I build a flash video player which works fine when exported to swf. However when I publish it (F12) does not loading the xml file. As a result video player stuck to frame 2 (where presented a List ...

How to get String representation of XmlType?

java xml jaxb

Is it possible to convert a javax.xml.bind.annotation.XmlType to the String representation of the XML?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.