dimanche 14 février 2021

How to avoid duplicated if statements

I have multiple services that implements interface with one method - execute(). Each service uses this method to execute some actions based on String value which, in original code is enum so those values are constant.

interface Service{
   public void execute();
}

class Service1 implements Service{
   //constructors
   public void execute(String type){
      if(type.equals("type1")){
       //do something
      }
   }
}

class Service2 implements Service{
   //constructors
   public void execute(String type){
      if(type.equals("type1")){
       //do something
      }
      if(type.equals("type2")){
       //do something
      }
   }
}

I want to avoid writing the same if statements each time I create new Service. Problem is, that each Service doesn't have to execute actions based on each string types. So Service1 executes action when type is equal to "type1", however Service2 execute actions based on "type1" and "type2".

I tried following solution:

class Main {
  public static void main(String[] args) {
    exec(new B(), "type2");
  }

  private static void exec(Service service, String type){
      if(type.equals("type1")){
       Init i = (Init)service;
       i.init();
      }
      if(type.equals("type2")){
       Action a = (Action)service;
       a.action();
      }
  }
}

interface Service{

}

interface Init{
  public void init();
}

interface Action{
  public void action();
}

class A implements Service, Init{
  @Override
  public void init(){
    System.out.println("init a");
  }
}

class B implements Service, Init, Action{

  @Override
  public void init(){
    System.out.println("init b");
  }

 @Override
   public void action(){
    System.out.println("action");
  }
}

The above code works, but I don't like using casting. I think it's not a good practice, also very unsafe. Could you suggest, what design pattern or other solution could I use here? I tried also with visitor, but I couldn't figure out the right implemntation with this case.

Aucun commentaire:

Enregistrer un commentaire