Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

1. Global Constants used in a applications by multiple projects.

Example:

  • Common logging strings
  • Container references like a database mapping reference used in WebSphere EAR's

2. Object Specific Constants

Example:

  • Employee pay rates for an Employee Object

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:

  • 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. As mentioned in the link above as Constant Interface Anti-pattern. .

Thanks in advance for thoughts and opinions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
285 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...