Jump to content

Constant interface

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Melchoir (talk | contribs) at 04:45, 22 August 2009 (Alternatives: link static import). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In the Java programming language, the constant interface anti-pattern describes the use of interfaces to define constants. This would enable classes implementing the interface to use the constants as member variables. However, since the usage of constants is considered an implementation detail, it is considered inappropriate to define an interface for this purpose.[1][2]

Use of this anti-pattern has three distinct effects:

  1. Pollutes the class with read-only variables that have little or no practical use.
  2. An instance of the interface has no practical use (since it has no methods).
  3. Without an IDE that resolves where the constant are coming from, tracking it back to its containing class or interface can be time consuming.

Example

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);
	}

}


Alternatives

Since Java 5, consider using static import[2] for such constants:

import static Constants.PLANCK_CONSTANT;
import static Constants.PI;

public class Calculations {

	public double getReducedPlanckConstant() {
		return PLANCK_CONSTANT / (2 * PI);
	}

}

References

  1. ^ Bloch, Joshua, Effective Java, 2nd Edition, p. 98
  2. ^ a b Sun Microsystems, Inc. (2004). "Static Import".