Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are most graceful alternatives to constant interfaces?

Tags:

java

constants

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?

like image 390
ring bearer Avatar asked Sep 15 '11 19:09

ring bearer


People also ask

Why constants should not be defined in 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.

Should interfaces have constants?

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!

Can interface be used for 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.

Should constants be in interface or class?

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.


1 Answers

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.

like image 88
Jon Skeet Avatar answered Sep 28 '22 01:09

Jon Skeet