Java – Is it a bad practice to have an interface to define constants

constantsdesignjavaprogramming practices

I am writing a set of junit test classes in Java.
There are several constants, for example strings that I will need in different test classes.
I am thinking about an interface that defines them and every test class would implement it.

The benefits I see there are:

  • easy access to constants: MY_CONSTANT instead of ThatClass.MY_CONSTANT
  • each constant defined only once

Is this approach rather a good or bad practice? I feel like doing so is a little like abusing the concept of interfaces.

You can answer generally about interfaces/constants, but also about unit tests if there is something special about it.

Best Answer

Joshua Bloch advises against this in his book titled Effective Java:

That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the classes' 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.

You can get the same effect with a normal class that defines the constants, and then use import static com.example.Constants.*;