Thursday, 10 November 2011

Idea1 - Avoid Switch/If conditions

While developing a web service, i came across a scenario where i need to create a Factory pattern to instantiate a Response class based on the Request string.

For example, if the Request is 'AuthenticateUserRequest', i need to create 'AuthenticateUserResponse'.

So i started writing an switch case like below

switch(requestName)
{
case "AuthenticateUserRequest":
return new AuthenticateUserResponse();
}

soon the method grows big, and i wanted to avoid this.

so i declared an dictionary with key value pair, with key being the request name and value being the response being the corresponding response class.

so it becomes

Dictionary responses = new Dictionary
{
{"AuthenticateUserRequest", new AuthenticateUserResponse()},
{"CreateOrderRequest", new CreateOrderResponse() }
};

-----
return responses[requestName].value.Clone();

No comments: