开发者

What are most graceful alternatives to constant interfaces?

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 r开发者_运维问答un-time, and should be avoided or tackled in a different way. What are elegant ways to represent this? Can enums be used instead?


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.


En enum is probably not a good idea unless all the parameters are closely related. With the two parameters in your example I'd say they are not closely enough related to qualify as an enum.

But it's not necessarily a Bad Idea to include a constants class / interface like this. It does have the advantage of being centralized, which means this configuration stuff can easily be moved outside of the program -- for instance to a properties file, a command-line decoder, a database or even a socket interface -- with minimal impact to the other classes. It's really a question of what direction the design will take.

Unless you are thinking of going down that path, however, I'd say static finals in the classes where the respective parameters are used is the way to go, as has been suggested already.


Turn the interface into a final class with a private constructor.


Use final non-instantiable class, i.e. one with a private constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜