Useless import static in Java

This post is about Java philosophy and feature introduction in language. Those days I develop a software piece in Java. Yeah, that is painfull for a Python user like me. I have a basic level in Java. I can write Java code but I'm still thinking as it was Java 1.4. While browsing a modern source code, I discovered the import static keyword.

import static java.lang.Math.E;

double result = E * 0.1;

Before Java 1.5 and import static, Java could only import packages or class. Now Java can import static members: functions or constants. The official documentation give two reasons:

  • avoid to declare local copies of constants;
  • avoid inheritance abuse (Constant interface anti-pattern);

local copies

I agree that local copies of constant are not a good idea for the maintenance. In the future you may want to change the constant, and having a copy is the best way to forget to modify the copy. Also having two constant for the same value has no sense.

constant factorization

I discovered that some java developers use interface and inheritance to factorize constant usage! This method is now officially discouraged and the anti-pattern Constant interface is on wikipedia.

Why not importing the class and use a qualified constant? In addition, direct import of member could lead to name space pollution. For java designer use qualified code is boilerplate code. Boilerplate is the word used in the changelog.

In my opinion this feature is absolutely useless. Except under particular circumstances, I don't see any added-value. And why do they chose to add the static keyword? The compiler could do that for you. This example show us how the community and usage can change the langage. I'm quite sure that if the Constant interface haven't been used, the import static keyword wouldn't exist.

By @Romain JACQUET in
Tags :