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
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.