Asdfasf

Sunday, August 24, 2014

EJ-31 Use Instance Fields instead of Ordinals

Ref: Effective Java by Joshua Bloch

All enums have an ordinal merhod which returns the numerical position of each enum constant in its type. You may be tempted to derive an associated int value from the ordinal



While this enum works, it is a maintenance nightmare to depend ordinal value which value changes in case of constants are reordered. The enum specification has this to say about ordinal: "Most programmers will have no use for this method, it is designed for use by general-purpose enum based data structures as EnumSet and EnumMap".

Luckily, there is a simple solution to these problem. Never derive a value associated with an enum form its ordinal; store it in an instance field instead:

 

No comments: