DEV Community

Discussion on: The Java Constants Interface Anti-Pattern

Collapse
 
ervin_szilagyi profile image
Ervin Szilagyi

My suggestion is to keep the constants as close to their usage as possible (as the reference article concludes). From my experience it is pretty rare to encounter such constants which represent a "global truth", like PI in the example above. If you encounter something like this, sure extract it if you want, but usually what happens is that your constant represents some kind of magic number of magic string which does make sense only in a given context. For those, just make a static final member variable and keep them private, it that is possible.
If you decide to extract the constant in an interface, don't implement that interface, statically importing the necessary constants would be enough. Although, this wont solve the shadowing problem. To solve that, I would avoid static imports as well, I would explicitly specify where my constant is coming from in case of every usage.

Collapse
 
darshitpp profile image
Darshit Patel

My suggestion is to keep the constants as close to their usage as possible

Yes, of course, that is true, and in such cases the usage is typically local or within the class itself. In these cases, it makes perfect sense to define constants using public static final within the classes they're being used. I, however, have encountered lots of usages of constants which are being shared across classes, and that is the point I was referring to.

Of course, constant interface shouldn't be implemented, and if someone really does that, one should have a quiet word with them in private :P