patternjavaMinor
Which one of the two enum implementation is better?
Viewed 0 times
theenumbetteronetwowhichimplementation
Problem
First Implementation
Second Implemenation
public enum ReviewFlowExample {
Draft {
@Override
public ReviewFlowExample getNext() {
return Review;
}
@Override
public ReviewFlowExample getPrevious() {
return null;
}
},
Review {
@Override
public ReviewFlowExample getNext() {
return Final;
}
@Override
public ReviewFlowExample getPrevious() {
return Draft;
}
},
Final {
@Override
public ReviewFlowExample getNext() {
return null;
}
@Override
public ReviewFlowExample getPrevious() {
return Review;
}
};
public abstract ReviewFlowExample getNext();
public abstract ReviewFlowExample getPrevious();
public boolean isDraft() {
return this.equals(Draft);
}
}Second Implemenation
public enum ReviewFlowExample {
Draft,
Review,
Final;
private ReviewFlowExample next;
private ReviewFlowExample previous;
static{
Draft.setNext(Review);
Review.setNext(Final);
Review.setPrevious(Draft);
Final.setPrevious(Review);
}
private ReviewFlowExample(){
}
public ReviewFlowExample getNext(){
return next;
}
public ReviewFlowExample getPrevious(){
return previous;
}
private void setNext(ReviewFlowExample next){
this.next = next;
}
private void setPrevious(ReviewFlowExample previous){
this.previous = previous;
}
public boolean isDraft(){
return this == Draft;
}
}Solution
Why not use the order you are setting up in the enum declaration? I played with this a while ago and came up with something like this (modified to fit your implementation above):
private enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE;
public Planet getNext() {
return this.ordinal() 0
? Planet.values()[this.ordinal() - 1]
: this;
}Code Snippets
private enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE;
public Planet getNext() {
return this.ordinal() < Planet.values().length - 1
? Planet.values()[this.ordinal() + 1]
: this;
}
public Planet getPrevious() {
return this.ordinal() > 0
? Planet.values()[this.ordinal() - 1]
: this;
}Context
StackExchange Code Review Q#6246, answer score: 5
Revisions (0)
No revisions yet.