Friday, April 04, 2008

Java 5 Static Import "Feature"

Wow, so first the people at Java 5 give us the convoluted generics which makes code as illegible as C++ templates, without any of the power of C++ templates. At least that provides the ability to avoid casting (but not really). But a new feature I haven't heard advertised much is the ability to import all the static methods of a class so that you don't have to prepend the name of the class when calling the method.

So, if you have a class:


public class StringUtils {
public static String parseString ( String a, String b ) { ... }
}


Whereas before Java 5 in order to call parseString() you would always have to write:


StringUtils.parseString( ... );


Now in Java 5 you can "statically" import all the static methods of the class, then use the method directly:


import static StringUtils.*;

parseString( ... ); // Calls StringUtils.parseString( );


Now, this basically flies in the face of everything that we have been told from the beginning of Java, which is that having static methods be attached to Classes was important for namespacing. Here we have a situation where finding what parseString() does without the help of an IDE is practically impossible. It looks like a local method call! If I saw this line in a piece of code and needed to figure out what parseString did, I would first look in the class, then start hunting through all of its superclasses (which in Java is usually quite a number). Then I would be thoroughly confused. Only after wasting a large amount of time would I think to inspect the import statements! Yet another language feature that is completely unuseable without the help of an IDE.

But the best part yet is the rationale for Sun's designers putting this "feature" into the language: it's to prevent a really dumb "antipattern". So, basically, they have tried to prevent an antipattern by introducing another one. Brilliant.

"Hey, instead of shooting someone with a gun, how about just stabbing them with a knife instead?" What a great idea. It's bad enough when Sun makes poor design decisions in Java. It's even worse when they follow that up with even worse band-aids to the original mistakes.

Here's a better solution: Developers should just type out the name of the class when using static methods! Since everyone in Javaland relies on IDE's to do everything anyway, it's just a series of mouse-clicks to call a static method anyway. At least that way everything stays true to Sun's original intentions for the language.