Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically cast to subclass to use correct method overload

I'm trying to make my code more polymorphic. Right now I have a superclass that has four different subclasses. I have a method that accepts the superclass as a type. I want to perform some generic actions before routing it to a different method to handle other actions. Here's what I am envisioning:

public void performSomething(Super object) { 
    //do some generic action each time to object
    object.setSuperProperty();

    //now route to appropriate method to perform specific action
    doSpecific(object);
}

private void doSpecific(SubA object) { }

private void doSpecific(SubB object) { }

private void doSpecific(SubC object) { }

private void doSpecific(SubD object) { }

This way if I want to add more functionality -- by creating a new subclass or whatever -- then I just need to add another method with the correct subclass type. However, this is not possible since the compiler complains about not having a doSpecific(Super object) method. Instead, in performSomething(Super object) I have to do an ugly:

if(object instanceof SubA)
    doSpecific((SubA)object);
else if(object instanceof SubB)
    doSpecific((SubB)object);
...

Is there a better way to do this than having to perform all the instanceof checks? Is there a design pattern that I'm not thinking of? I know that I'll lose the compile-time type check safety, but just curious what other solutions could possibly exist.

edit: Forgot to mention this. performSomething and doSpecific are part of an unrelated class I'll call ClassA. I considered creating an abstract method in the Super class so that the subclass could properly implement it. The problem is that performSomething and doSpecific depend on roughly 8 different members of ClassA. So if I wanted to delegate the method to the subclass it would require a ton of parameters like subB.doSpecific(int, int, String, String, Object, int, long, blah, blah); which I'm not sure is better than the original instanceOf check. This would also create a tight coupling between ClassA and the Super/Sub classes I have, when doesn't seem right since I just need to read values from them.

like image 764
telkins Avatar asked Nov 01 '22 04:11

telkins


1 Answers

I recommend the Command Pattern.

That means: Every of your subclasses implements a doSpecific() method. Then your initial method looks like this:

public void performSomething(Super object) { 
    //do some generic action each time to object
    object.setSuperProperty();

    //now route to appropriate method to perform specific action
    object.doSpecific(...);
}

The compiler picks the method of the subclass automatically - no instanceOf check for you.

like image 168
exception1 Avatar answered Nov 08 '22 14:11

exception1