Item 19: Use interfaces only to define types

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

 

2.  The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class’s exported API.

 

3.  The constant interface represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a non-final class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.

 

4.  If the constants are strongly tied to an existing class or interface, you should add them to the class or interface. (i.e. Integer.MIN_VALUE, Double.MAX_VALUE)

 

5.  If the constants are best viewed as members of an enumerated type, you should export them with an enum type.

 

6.  In other cases, you should export the constants with a non-instantiable utility class. (Make the constructor private to prevent instantiation)

 

7.  If you make heavy use of the constants exported by a utility class, you can avoid the need for qualifying the constants with the class name by making use of the static import facility, introduced in release 1.5.

你可能感兴趣的:(enum,Effective Java)