Tuesday, February 26, 2008

Static Import

When a set of constants are tightly tied with a set of classes or package - the normal method used is to define the constants in an interface and implement that interface in the class. The advantage is that we can refer to the constants without qualifying them with a class name, like - Math.PI.
 
But this is a bad idea. The Constant Interface Antipattern (Effective Java, Item 17) explains the drawbacks:
(1) it becomes part of the class API, which can confuse the eventual users of the class
(2) all the subclasses will unnecessarily have the interface as part of their inheritance tree
 
Workaround is to use a static import.
 
The static import construct allows unqualified access to static members without inheriting from the type containing the static members. We inherit the static members either individually
 
    import static java.lang.Math.PI;
 
or en masse:
 
    import static java.lang.Math.*;
 
Once imported, the static members can be used without qualification:
 
    double r = cos(PI * theta);
 
We can also import static methods individually
 
    import static java.lang.Math.random;
 
The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.
 
We should take care that this feature is used sparingly, otherwise the code will become unreadable, making it difficult to trace which class a static member belongs to. Also, if only one or two members are required, it is advisable to import them individually, rather than importing all the static members.
 
(http://java.sun.com/j2se/1.5.0/docs/guide/language/static-import.html)

No comments: