Another 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?

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.

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.