Search code examples
refactoringinstanceofvisitor-pattern

Eliminating a conditional statement with instanceOf checks


I have the following method:

@Override
public <T> T method(T object){
    if(object instanceOf Type1){
    ...
    }
    elseif(object instanceOf Type2){
    ...
    }
    ...
}

object is always of type SuperType and Type1, Type2, ... are all subtypes of SuperType. I don't have acces to any of the types SuperType, Type1, etc., so I cannot change them.

I´d like to eliminate this structure that has a lot of if-s and instanceOf checks. I tried implementing the Visitor pattern for this purpose, but it didn´t work, as I cannot modify any of the types mentioned above.

Does anyone know a nice solution for this example? Thank you!


Solution

  • You could have a dispatch table.

    private final static Map<Class<?>, Handler> dispatch = ....
    // contains things like  Type2.class -> Type2Handler
    
    dispatch.get(object.getClass()).handle(object);
    // may need to iterate superclasses if that is a concern
    

    Not sure if that is better, though.