Another #java puzzle:
Interface A is implemented by classes B and C. I call a method that returns an A and want to do different things depending on whether I actually get back a B or a C. Is there a cleaner way than this?
A result = otherObject.foo();
if (result instanceof B) {
B b = (B)result;
doSomething(b);
} else {
C c = (C)result;
doSomething(c);
}
I can't change doSomething(b) into b.doSomething() because (for security reasons) I don't want otherObject to be able to doSomething.
instanceof feels dirty.
Ideas?
@peterdrake That's as clean as it gets with current Java. Soon we'll get pattern matching, which will make that nicer.
Other variations are:
if (implA.getClass().isAssignableFrom(object)) {
((implA)object).doIt();
}
Solution: double dispatch. I replaced:
A result = otherObject.foo();
if (result instanceof B) {
B b = (B)result;
d.doSomething(b);
} else {
C c = (C)result;
d.doSomething(c);
}
with :
otherObject.foo().doSomething(d);
where B and C have different definitions of doSomething.
As desired, otherObject still can't call doSomething, even on Bs and Cs it creates, because it doesn't have access to d.