Wednesday, April 15, 2009

Constant Interfaces

A constant interface is one that contains no methods, only static final fields, each declaring a constant. Below is an example:
public interface UniversalConstants {
//Speed of light in m/s
static final int SPEED_OF_LIGHT = 299792458;

//Newtonian constant of gravitation in m^3 * kg^-1 * s^-2
static final double GRAVITATION = 6.6742867e-11;
}

There were times in the past that I've used such interfaces in classes that needed the constants. This is a poor use of interfaces. An interface serves as a type that tells you what a class that implements that interface can do with an instance of it. There is nothing of this kind when using constant interfaces. How can we avoid this? (At least) In two ways. One, define the constants inside your class, if you feel that there is a strong relationship between those constants and you class. The other way is to use a utility class that cannot be instantiated, like below:
public final class UniversalConstants {
//Speed of light in m/s
public static final int SPEED_OF_LIGHT = 299792458;

//Newtonian constant of gravitation in m^3 * kg^-1 * s^-2
public static final double GRAVITATION = 6.6742867e-11;
}

When using these constants from within your own class, you can add a static import declaration and you're done!

No comments: