Almost Useful: if instanceof
While often times if (x instanceof Y) indicates a problem that should be solved with proper use of polymorphic methods, it sometimes is unavoidable (.equals(Object o) implementation for example). A common idiom is:
if (x instanceof Y) {
Y y = (Y) x;
}
Of course, this makes sense from a utility point of view, you know that it is a Y object, and so you want Y functionality from it. From a programmers point of view though, it is terribly redundant in many ways. In many cases, static analysis can tell the compiler that when you are in the block of that if statement, that x is indeed a Y object, why then should I be forced to cast to Y? Why can’t the compiler figure out the type for me?
This becomes even more useful if we combine the concept with the fully useful Type Intersection (Not yet implemented). If both of these features were implemented, then you could write something like:
public <T extends Comparable<T>> void sort(List<? extends T> list) {
if (list instanceof RandomAccess) {
/* list compile-time type here would be List<? extends T>&RandomAccess. */
sort(list);
} else {
/* Other type of sort implementation. */
}
}
public <T extends Comparable<T>> void sort(List<? extends T>&RandomAccess list) {
/* Random access sort implementation */
}
This type of static analysis feature could be extended to predict NPE’s and redundant checks. Heck, the IDE I use tells me when I’ve accessed something when it might be null, or when my inner-if statement is a subset of the outer. It even has shortcuts for adding the cast in the if (x instanceof Y) {} blocks.
Tags: instanceof, missing feature., static analysis, type intersection

November 25th, 2007 at 9:53 am
Very nice articles. I subscribed to your RSS.
Keep up the good work
Alfred