tejaswini tejaswini - 7 months ago 13
Java Question

How to reduce if else jungle from my controller?

I have a java controller class, when ever save action is invoked in any item say Product or coverage or Limit , it calls the controller save method and a parameter is passed. The if logic in the controller checks the argument and call the save method of the appropriate object. The if logic is increasing day by day. Can any one suggest better design pattern?

Code:

public class Product {
public void save(PolicyData p){
//logic here
}
}

public class Coverage {
public void save(PolicyData p){
//logic here
}
}

public class Limit {
public void save(PolicyData p){
//logic here
}
}

public class Controller {

private Product pr=new Product();
private Limit lim=new Limit();
private Coverage cov=new Coverage();


public void save(PolicyData p,String item){
if(item.equals("Product")){
pr.save(p);
}if(item.equals("Coverage")){
cov.save(p);
}if(item.equals("Limit")){
lim.save(p);
}
}
}

Answer
  1. Create an interface that has save method
  2. Implement the method in your object
  3. In your controller create a map to hold objects against the key that you are comparing now in your if

code:

public interface Myinterface {
public void save(PolicyData p);
}

public class Product implements Myinterface{
public void save(PolicyData p){
    //logic here
}


public class Controller {


    private static HashMap<String,Myinterface> map=new HashMap<String,Myinterface>();

    public Controller(){
        map.put("Product", new Product());
        map.put("Product", new Limit());
        map.put("Product", new Coverage());
    }

    public void save(PolicyData p,String item){
    Myinterface m=map.get(item);
    m.save(p);
    }
}
    }