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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Abuse of ordinal to derive an associated value - DON'T DO THIS | |
public enum Ensemble { | |
SOLO, DUET, TRIO, QUARTET, QUINTET, | |
SEXTET, SEPTET, OCTET, NONET, DECTET; | |
public int numberOfMusicians() { return ordinal() + 1; } | |
} |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum Ensemble { | |
SOLO(1), DUET(2), TRIO(3), QUARTET(4), QUINTET(5), | |
SEXTET(6), SEPTET(7), OCTET(8), DOUBLE_QUARTET(8), | |
NONET(9), DECTET(10), TRIPLE_QUARTET(12); | |
private final int numberOfMusicians; | |
Ensemble(int size) { this.numberOfMusicians = size; } | |
public int numberOfMusicians() { return numberOfMusicians; } | |
} |
No comments:
Post a Comment