Item 22: Use interfaces only to define types

Interfaces should be used only to define types. They should not be used merely to export constants.

The constant interface pattern is a poor use of interfaces

// Constant interface antipattern - do not use! 
public interface PhysicalConstants { 

  static final double AVOGADROS_NUMBER = 6.022_140_857e23; 
  static final double BOLTZMANN_CONSTANT = 1.380_648_52e-23; 
  static final double ELECTRON_MASS = 9.109_383_56e-31;

}

If the constants are best viewed as members of an enumerated type, you should export them with an enum type (Item 34)


If the constants are NOT strongly tied to an existing class or interface, export the constants with a noninstantiable utility class

public class ConstantsFoo {

	private ConstantsFoo(){} // prevent instantiation
	
	public static final double AVOGADROS_NUMBER = 6.022_140_857e23;
	public static final double BOLTZMANN_CONST = 1.380_648_52e-23;
	public static final double ELECTRON_MASS = 9.109_383_56e-31;
}

Leave a Reply

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