It's been told me (and I have seen this statement in a few other places) that it's not recommended to store your constants in a separate class in Java, in order to use them in the other classes. But I haven't seen anywhere WHY is it so. What is the reason I should not store them in their own interface/class?
I came from C to Java and in C i would just make a .h
file where i defined constants with #define
Even if constants are related, they should not be put into a single file. The wrapper classes in Java is a good example of related constants being defined in their own class files rather than in a WrapperConstants file.
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.
You should do it in a class. An Interface is a description of available methods, properties etc that class users can access - by implementing an interface, you guarantee that the members declared in the interface are available to the user.
You declare a constant within a procedure or in the declarations section of a module, class, or structure.
Constants in a dedicated file are frowned upon for stylistic reasons. Having a class dedicated to constants can encourage developers to add increasing numbers of unrelated (undocumented?) constants to a file that slowly bloats out of control.
By contrast, having constants associated with the classes they are related to is a more scalable and readable design.
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