mercredi 17 juillet 2019

How to refactor multiple switch statments

I've got a rest endpoint where based on Enum value I call method of specific service. All services extends after the same abstract class.

public abstract class BaseService{
  someMethod()
}

public class ServiceA extends BaseService{
  @Override
  someMethod()
}

public class ServiceB extends BaseService{
  @Override
  someMethod()
}

public class RestEndpoint {
  @Inject
  ServiceA serviceA
  @Inject
  ServiceB serviceB

  public void someEndpoint(Enum value){
    switch (value){
    case 1:
       serviceA.someMethod();
    case 2:
       serviceB.someMethod();
   }
  }
}

The thing is, there might be a lot more services, and I wonder if there is some better way of doing it. I thought about implementing strategy pattern, but I don't know if that wouldn't be 'overkill' since there will be at most ~10/15 services.

Aucun commentaire:

Enregistrer un commentaire