Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best design pattern/approach for a long list of if/else/execute branches of code

I have a "legacy" code that I want to refactor.
The code basically does a remote call to a server and gets back a reply. Then according to the reply executes accordingly.
Example of skeleton of the code:

public Object processResponse(String responseType, Object response) {
    if(responseType.equals(CLIENT_REGISTERED)) {  
       //code  
       //code ...
    }  
    else if (responseType.equals(CLIENT_ABORTED)) {
       //code  
       //code....
    }    
    else if (responseType.equals(DATA_SPLIT)) {
      //code
      //code... 
   }  
   etc  

The problem is that there are many-many if/else branches and the code inside each if is not trivial.
So it becomes hard to maintain.
I was wondering what is that best pattern for this?
One thought I had was to create a single object with method names the same as the responseType and then inside processResponse just using reflection call the method with the same name as the responseType.
This would clean up processResponse but it moves the code to a single object with many/many methods and I think reflection would cause performance issues.
Is there a nice design approach/pattern to clean this up?

like image 889
Jim Avatar asked Mar 07 '15 16:03

Jim


People also ask

What is the best approach in designing patterns in coding?

One of the most popular design patterns used by software developers is a factory method. It is a creational pattern that helps create an object without the user getting exposed to creational logic. The only problem with a factory method is it relies on the concrete component.

What is the best design pattern in Java?

Singleton Design Pattern: It follows “define a class that has only one instance and provides a global point of access to it“. The class must ensure that only a single instance should be created and a single object can be used by all other classes. Advantages: It is designed to save memory.


1 Answers

Two approaches:

  1. Strategy pattern http://www.dofactory.com/javascript/strategy-design-pattern
  2. Create dictionary, where key is metadata (in your case metadata is responseType) and value is a function.

For example:

Put this in constructor

responses = new HashMap<string, SomeAbstraction>(); responses.Put(CLIENT_REGISTERED, new ImplementationForRegisteredClient()); responses.Put(CLIENT_ABORTED, new ImplementationForAbortedClient());

where ImplementationForRegisteredClient and ImplementationForAbortedClient implement SomeAbstraction

and call this dictionary via responses.get(responseType).MethodOfYourAbstraction(SomeParams);

If you want to follow the principle of DI, you can inject this Dictionary in your client class.

like image 195
Sattar Imamov Avatar answered Oct 27 '22 11:10

Sattar Imamov