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.
What is the difference between Enumeration interface and enum in Java? What is the difference between Enumeration interface and enum in Java? Enum in Java is a datatype which stores a set of constant values. You can use these to store fixed values such as days in a week, months in a year etc.
You can use this class as a type in any entity or value object, as for the following CardType : Enumeration class: Jimmy Bogard. Enumeration classes Steve Smith. Enum Alternatives in C#
For Situation 2: Design Approach: Apply the use of Enums to represent those constants as a object. If the constant string belongs to the class and you only need the string value keep in the class that uses it Don't use an Interface for situation 1.
An enum class is an enumeration of values, generally containing all possible values, or at least all values the code supports, from some reasonably small set. Every instance of an enum class is a public static final member of the class, with every instance initialized statically when the class is loaded.
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.
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):
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