As I’ve always understood it, the main cases where an instanceof is appropriate are:
- Implementing
Object.equals(Object). So if I were writing aListclass, and not extendingAbstractListfor whatever reason, I would implementequals(o)by first testingo instanceof List, and then comparing elements. - A significant (algorithmic?) optimization for a special case that does not change semantics, but only performance. For example,
Collections.binarySearchdoes aninstanceof RandomAccesstest, and uses a slightly different binary search forRandomAccessand non-RandomAccesslists.
I don’t think instanceof represents a code smell in these two cases. But are there any other cases where it is sensible to use instanceof?
Legacy code or APIs outside of your control are a legitimate use-case for
instanceof. (Even then I’d rather write an OO layer over it, but timing sometimes precludes a redesign like that.)In particular, factories based on external class hierarchies seem a common usage.