Image

Imageshmuelisms wrote in Imagejava_dev 🙃creative

interfaces + instanceof / collection = BAD??

Hello all, while I'm a experienced programmer, I'm pretty new to Java, so I was wondering about this issue I have. Java Practices explains here, why one should avoid the instanceof operator. I fully understand their reasoning, why polymorphism is better. But this makes the hidden assumption that your relevant objects all share a common base class. What if this is not the case??
public interface Foobarable {
    public void foobar();
}
========================================
...
void foobar(List oList) {
    for (Iterator oIter = oList.iterator(); oIter.hasNext(); ) {
        Object listItem = oIter.next();
        if (listItem instanceof Foobarable) 
            ((Foobarable)listItem).foobar();
    }
}
...

Is this "acceptable" usage, given that the List will contain different types of objects, that do NOT share a common base class. Is there a BETTER more elegant way to do this??

EDIT: Fixed class-name typo in final line. Oops.