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

wxPython in Python 3.4.1

python python-3.x wxpython

I'm relatively new to Python programming, so apologies in advance if this question seems stupid. I'm trying to download a new Python editor (drpython) that is written with wxpython. I have Python...

MS Access IN operator not returning rows

ms-access in-clause

Using an MS Access database (I know), the query below

A good way to create unique entity keys in Python

python google-app-engine key md5

Suppose I have an entity in my datastore that I know it can have a unique key_name deriving from a combination of it's properties:

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.