Is it a good practice to write an enum as a class file in java?
https://softwareengineering.stackexchange.com/questions/344586
Frage
I am constructing an enum Flower
which contains the fixed set of constants for Flowers as described below. I'm writing it in a separate file and importing it to other classes so that it could be used across my project.
Is it a good practice to write an enum in a separate file in Java. Can someone give me some advice on this.
public enum Flower {
Jasmine(1),
Lotus(2),
Lilly(3),
Sunflower(4),
Tulip(5),
Daria(6);
private int flowerValue;
public Flower(int value) {
this.flowerValue = value;
}
public int getFlowerValue() {
return this.flowerValue;
}
public String getFlowerName() {
return this.name();
}
}
Lösung
Yes, it absolutely is. Its the same as with usual classes and polymorphism:
// this code in approx. 100 places
int flowerValue;
switch(flower) {
case Flower.Jasmine: flowerValue = 1; break;
case Flower.Lotus: flowerValue = 2; break;
...
case Flower.Daria: flowerValue = 6; break;
}
// good luck adding a new flower...
versus
// this code in approx. 100 places
int flowerValue = flower.getFlowerValue()
In this particular case it seems as if flower.ordinal()
would work just as well.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit softwareengineering.stackexchange