Reputation: 1298
I have been reading a lot of posts on this site regarding the usage of constants.
Question: When should I use Enums for constants, vs using classes or interfaces.
I see 2 key situations I am looking to address.
Example:
Example:
From everything I have read this is what I think I have a grasp on and what I am looking for an opinion on.
For situation 1:
Design Approach: Use a final class and a static import.
Seen here: What is the use of interface constants?
For Situation 2: Design Approach: Apply the use of Enums to represent those constants as a object.
Additional points to remember:
Thanks in advance for thoughts and opinions.
Upvotes: 15
Views: 13364
Reputation: 38899
Global constants used by different projects: Enum
Better to use Enum
over public static final
members in a class. More clean and easy to understand I guess.
Object specific constants: public static final members in Class
. Because, they are needed only within the scope of the object, then no need to created a new Enum for that.
Nice read
Update (fixed broken link):
Upvotes: 3
Reputation: 15363
It sounds like almost everything you've listed for both numbers 1 and 2 belong in configuration files or database tables.
Do you want to re-compile code when your employee's get a raise or a page name changes?
Unless there is a compelling reason everything else that is constant should be modeled as an enum. This way you realize the benefits of fast object equality comparisons and you avoid problems associated String constants.
The scope of those enums however is application specific. If the enumeration is only used by a class that it should be a private enum. If it is shared by multiple classes then it should be in its own class definition file.
Upvotes: 0
Reputation: 24316
Global constants as you put it should actually be in a properties file as it allows each application to configure them individually without a code modification. For object specific constants my general rule of thumb on Enum
versus static final
I typically lean towards how many elements there are to have and how related those elements are. If there is a big relation between them such as Suits
in a deck of Cards
then I would go for the enum. If it is default age for a user, then this becomes a final as there is no purpose to making it an enum as it would not need to be referenced in many areas. These are just some thoughts on each of the ways I have approached it.
Upvotes: 12