Static Import

I never liked seeing people put constants in an interface and then implementing that interface in a class so that they can have direct access to those constants. That always seemed wrong to me and now this Sun article, Static Import, verifies my intuition.

In order to get around this, people sometimes put static members into an interface and inherit from that interface. This is a bad idea. In fact, it’s such a bad idea that there’s a name for it: the Constant Interface Antipattern (see Effective Java Item 17). The problem is that a class’s use of the static members of another class is a mere implementation detail. When a class implements an interface, it becomes part of the class’s public API. Implementation details should not leak into public APIs.

The suggested method is to use a static import.

import static java.lang.Math.PI;

However the article suggests using this sparingly.

Only use it when you’d otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

You can also do static import of methods.

import static com.betweengo.util.CollectionUtils.isEmpty;

However I would never do this, I like knowing where my static methods come from.

Leave a Reply

Your email address will not be published. Required fields are marked *