I have a project that consists of 5 different packages in Java. All of them contain classes that have magic numbers and hardcoded strings for which I'm looking to create constants. I would like to know what is best practice. Should I create one Constants class for all of the constants in the program that all classes can import? Or would it be more efficient to split up the constants into multiple, smaller files?
-
1More efficient regarding what? Running speed? – Kayaman Jul 19 '17 at 16:35
-
1imho, you should not mix constants which are related to distinct concerns in the same class. – Arnaud Denoyelle Jul 19 '17 at 16:35
-
Do any of these constants or magic values change according to which environment the code is on? For instance, a dev connection string vs a prod connection string? – oooyaya Jul 19 '17 at 16:37
-
1ResourceBundle(s) and Properties files are wonderful things. – Elliott Frisch Jul 19 '17 at 16:37
-
3A constants class is an antipattern. Constants belong in the class to which they pertain. `Integer.MAX_VALUE` is good; IntegerConstants.MAX_VALUE would be a pointless separation. And you definitely should not make one class containing constants from all the packages. – VGR Jul 19 '17 at 16:47
-
Consider using `enum`s. – Andrew S Jul 19 '17 at 16:53
-
While named constants are good, certainly better than inline literals in 19 out of 20 cases, I see no point per se in moving them away from the class where they belong. Think lose coupling and high cohesion (if you don’t know the terms, look them up). – Ole V.V. Jul 19 '17 at 16:57
1 Answers
In terms of best practices, see the Principle of Least Privilege.
You should extract inline hard coded constants, but you should not put all constants into one monolithic class. Instead, split the constants into contextually appropriate classes ("multiple smaller files") and keep those classes only at the package level they need to be referenced properly.
If the value applies only to one particular class (aka private static final
), there is no need to lift this value out of the class. It would only create more work to keep it elsewhere if it is only referenced in that one place.
If the value acts like a global variable or needs to be accessed in many different classes (aka public static final
), extracting related values into a separate class makes sense but is probably a code smell you should investigate.
Since you are using packages, consider using package-private (static final
) to isolate your configuration values to a single package that needs it.
Consider using configuration/properties files to inject values instead of explicitly hard coding them in a class at all. Depending on your needs, you may use simple Java Properties or there are many libraries/frameworks which can help you handle properties, such as Spring.

- 1,039
- 3
- 12
- 26