jga: Now, I see a use for 1.5 static method imports

For quite some time I’ve considered the static method import in java 1.5 rather useless and only usefull for lazy programmers who wanted to avoid typing “java.text.” in front of “NumberFormat”. The page
jga: using the java 1.5 forloop shows an application of jga’s generic functor objects. By making use of the static import feature the code is actually very easy to read and reminds me more of perl than of java:

for(PlantType f : unique(transform(fruitsByType, getType))) {

The same code without static method import would lead to either artificially short method and class names or make the code unreadable:

for(PlantType f : Algorithms.unique(Algorithms.transform(fruitsByType, getType))) {

Like every powerful feature, also static method import is tempting and likely to be over-used. Nevertheless it solves today’s problems.

Another example where static method import helps is JUnit. The Assert class wich provides a nice set of assert helper methods is extended by the TestCase class which all Test classes have to extend. This is annoying because JUnit dictates a implementation hierarchy just to have the possibility of calling assertEquals instead of Assert.assertEquals. The static import of all methods in Assert which are needed decouples the tests’ implementation hierarchy from the testing framework. TestNG, an alternative Java testing framework, is free from this coupling and relies on static method import. Please note that you can still extend the Assert class to your test case class if you dislike static method import or it’s not available.

Updated the 2nd example according the the comment received from “Complex Lex”.

{ Comments are closed! }