I've read that question & answers: What is the best way to implement constants in Java?
And came up with a decision that enum is better way to implement a set of constants. Also, I've read an example on Sun web site how to add the behaviour to enum (see the link in the previously mentioned post). So there's no problem in adding the constructor with a String key to the enum to hold a 开发者_运维技巧bunch of String values.
The single problem here is that we need to add ".nameOfProperty" to get access to the String value. So everywhere in the code we need to address to the constant value not only by it's name (EnumName.MY_CONSTANT), but like that (Enum.MY_CONSTANT.propertyName).
Am I right here? What do you think of it?
Yes, the naming may seem a bit longer. But not as much as one could imagine...
Because the enum class already give some context ("What is the set of constants that this belong to?"), the instance name is usually shorter that the constant name (strong typing already discriminated from similar named instances in other enums).
Also, you can use static imports to further reduce the length. You shouldn't use it everywhere, to avoid confusions, but I feel that a code that is strongly linked to the enum can be fine with it.
In switches on the enum, you don't use the class name. (Switches are not even possible on Strings pre Java 7.)
In the enum class itself, you use the short names.
Because enums have methods, many low-level codes that would make heavy use of the constants could migrate from a business code to the enum class itself (either dynamic or static method). As we saw, migrating code to the enum reduces the long names uses even further.
Constants are often treated in groups, such as an
if
that test for equality with one of six constants, or four others etc. Enums are equipped withEnumSets
with acontains
method (or similarly a dynamic method that returns the appropriate group), that allow you to treat a group as a group (as a secondary advantage, note that these two implementations of the grouping are extraordinarily fast - O(1) - and low on memory!).
With all these points, I found out that the actual codes are much much shorter !
With regard to the question about constants - enums should represent constants that are all the same type. If you are doing arbitrary constants this is the wrong way to go, for reasons all described in that other question.
If all you want are String constants, with regard to verbose code you are right. However, you could override the toString() method return the name of the property. If all you want to do is concatenate the String to other Strings then this will save you some extra verbosity in your code.
However, have you considered using Properties files or some other means of internationalisation? Often when defining dets of Strings it is for user interface messages, and extracting these to a separate file might save you a lot of future work, and makes translation much easier.
精彩评论