Reputation: 85
There are some constants and enumerations in a project, and each one is used by some other classes.
As a design pattern, is it acceptable to create a class for constants and enumerations definition? Or is there a better way to define and use those constants?
Upvotes: 0
Views: 66
Reputation: 1329
If I were you I create a constant container class packege by package. Just span the logically coherent parts together. Otherwise you will increase the the coupling and dependency. And the most general constants (problem domain independent ones) take place in the utility package's constant container class.
Upvotes: 0
Reputation: 802
It depends on the problem domain. Generally speaking it is rather standard practice to keep them in Java enumeration. The question is - how would you like to use those constants? I have such experience, that constants being hold in interfaces/enumerations are being duplicated and created over and over again due to lack of the knowledge of developers of past constants. In the result, there are many files as such Constants.java
, BusinessLogic.java
, AppConstants.java
etc.. It causes big overwhelm over the purpose and then you don't know if the some constant, lets say APP_MODE
should be used from Constants.java
or AppConstants.java
?
One of the solutions is to keep those constants in one (or many?) properties files and inject thme using spring' @Value
annotation.
You may group by using some prefixing, building groups separated by dot.
One of the advantages of the property files is that you keep one Java logic of using properties, but you still can provide property file (which may vary depending on application). A lot of flexibility, no redundancy.
Another solution is to create one Service
to provide properties / constants from database. You can differentiate the values over diffrent environements, but that's another story.
Upvotes: 1