Thursday, April 2, 2009

Static Import In Java 5

Constant Interface Anti pattern is a real hot topic of discussion in java, after browsing the web for hours I am not sure whether to use it or avoid it.
Constant Interface is a interface which defines some public static final constants. And when we need those constants we can implement the Interface and uses the defined constants or we can access the static constants as InterFaceName.ConstantName.

The book Effective Java by Joshua Bloch discusses this problem he calls it "Constant Interface Anti pattern."
Poor use of interfaces and  Exposes Implementation Detail are some of the issues why author advocates to avoid it.

public interface Constants {
 
    public static final double PI = 3.14159;
 
    public static final double PLANCK_CONSTANT = 6.62606896e-34;
 
}
 
 
public class Calculations implements Constants {
 
    public double getReducedPlanckConstant() {
        return PLANCK_CONSTANT / (2 * PI);
    }
 
}


Java 5 comes with a Static Import concept. We can solve the "Constant Interface Anti pattern." by using static import , as demostrated by the following example.

import static Constants.PLANCK_CONSTANT;
import static Constants.PI;
 
public class Calculations {
 
    public double getReducedPlanckConstant() {
        return PLANCK_CONSTANT / (2 * PI);
    }
 
}

The static import declaration is analogous to the normal import declaration. 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.

No comments :

Post a Comment