Let’s say I have the following classes:
public interface X {
...
}
public class A implements X {
...
}
public class B implements X {
...
}
Now let’s say I have a method somewhere that takes an object of type X, and must handle each implementation of X differently. The naïve approach is:
public void doSomething(X x) {
if(x instanceof A)
doSomethingA((A) x);
else if(x instanceof B)
doSomethingB((B) x);
}
…but this seems particularly ugly and not polymorphic. What is the clean way of handling such a situation in general?
EDIT: Sure, it would be easy if I could push the implementation of doSomething() to classes A and B, but what about in situations where that doesn’t make sense? i.e. doSomething() is defined on a class C and the implementation is highly dependent on C’s internal state.
It’s easy:
UPDATE: Ok, seems here we have some algorithm in C which dependants on C’s state as well as on A/B differences. Then I would try to split that algorithm so that C class has only a common implementation for both A and B, and A-/B-dependent parts should go to an appropriate class as a particular implementation of the same method which is invoked in C. If possible, C’s state can partially be passed to A’s and B’s doSomething