Recently I came across a piece of code wherein I found an interface with only constants. And those constants were accessed in classes using static imports. The constants were more in number (around 30 to 50).
Personally, I don’t think it’s a good practice. Thats why its called as Constant Interface Antipattern according to Effective Java. I don’t find any good reason to go for this kind of coding.
Also, static import should be used ONLY if there are few constants to be imported by many classes in our application.
Can anyone of you please let me know if there are any other good reasons to go for constants only interface?
Certainly prior to the introduction of enums, if you had a large collection of constants that needed to be shared between a number of classes, a Constant Interface was probably the most pragmatic way to do so.
If those constants were only used in one class then the comments in other answers (‘a pattern to avoid’) are quite valid – they would be most useful if declared by the class that uses them.
With newer versions of Java, I’d move towards enums with a constructor that allows value(s) to be set. However it’s still the case that if the set of values are only used by a single class, it makes most sense to declare them within that class rather than separately.