Right way of defining constants - Interfaces or Classes?
807603Jan 23 2008 — edited Jan 24 2008Two widely used ways to define constants in java projects are:
1. Interfaces - Define constants in interfaces, they automatically become static, final and then implement the interface in concrete classes that need those constants.
2. Classes - Use normal classes and define explicitly as static, final. Use CLASS_NAME.CONSTANT_NAME to access the constant in concrete classes.
I have gone through the web on Best-practices for defining constants and its strongly recommended for not using Interfaces for defining constants.
"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. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it 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 nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. " from Effective Java, Joshua Bloch
What is your take on this?
Rgds