I had been looking at some code developed by an off-shore group. I see at least one "constant interface" per module defined. Example (not real world) :
public interface RequestConstants{
//a mix of different constants(int,string,...)
public static final int MAX_REQUESTS = 9999;
public static final String SAMPLE_REQUEST = "Sample Request";
}
Per my understanding it is an anti-pattern as these does not any utility in run-time, and should be avoided or tackled in a different way.
What are elegant ways to represent this? Can enums
be used instead?
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.
As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class. And hence: Interfaces should only be used to define contracts and not constants!
Interface ConstantsA Java interface can contain constants. In some cases it can make sense to define constants in an interface. Especially if those constants are to be used by the classes implementing the interface, e.g. in calculations, or as parameters to some of the methods in the interface.
Java programmers commonly define constants inside their interfaces, if it makes design sense. You can do so using variables in an interface because the values will be present instantly at runtime and their values shared among all classes implementing your interface, because they are static and final.
I prefer to put constants in the class where they make they're most relevant, and then if I have to refer to them elsewhere, just do so - possibly using static imports if that makes sense (e.g. for Math.PI
).
The only real reason to put constants in interfaces was to allow you to "implement" the method-free interface and get access to the constants via their simple names without any further qualification. Static imports remove that reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With