lundi 25 septembre 2017

Interface segregation principle - Java

I have an interface

interface XXXCommandHandler(){
    void parse(String something);
    String response();
    String additionalResponse();
}

  1. Some of the classes that implement XXXCommandHandler do not implement additionalResponse().
  2. I am using ApplicationContextManager.getInstance().getBeansOfType(XXXCommandHandler.class) to get the classes that implement XXXCommandHandler
  3. Then call parse, response and additionalResponse
  4. Since some do not implement additionalResponse I am forced to return null.

I can think of the following

  1. Instead of returning null on classes that do not implement additionalResponse, declaire additionalResponse as default method and return null / or make it return Optional etc and override it on the classes that implement additionalResponse method.
  2. Ugly way :- return null in all the classes that do not implement additionalResponse
  3. Create two different interfaces XXXCommandHandlerParser() with parse and response method and XXXCommandHandlerAddtionalresponse() with additionalResponse method extending XXXCommandHandlerParser i.e

    interface XXXCommandHandlerParser(){

        void parse(String something);
        String response();
    
    }
    
    

    interface XXXCommandHandlerAddtionalresponse() extends XXXCommandHandlerParser {

        String additionalResponse();
    }
    
    
  4. But if I do #3 I had to change ApplicationContextManager.getInstance().getBeansOfType(XXXCommandHandlerAddtionalresponse.class).

  5. If I do #4 then classes that do not implement additionalResponse or that do not implement XXXCommandHandlerAddtionalresponse will not be picked up.

Can you think of any elegant way?

Aucun commentaire:

Enregistrer un commentaire