I feel like I am just missing something or maybe this is not the use of enum. Pretty much I know I could clean up this code using an enum:
int bookTypeId = 1; //dynamic
String bookTypeName;
switch (bookTypeId) {
case 1:
bookTypeName = "Fantasy";
break;
case 2:
bookTypeName = "Horror";
break;
case 3:
bookTypeName = "Action";
break;
default:
bookTypeName = "Error";
}
And so I did, I stored it in another class and it looks like:
public static enum BookType {
HORROR("Horror"), FANTASY("Fantasy"), ACTION("Action"), ERROR("Error");
private String name;
BookType(String name) {
this.name = name;
}
public String getType() {
return name;
}
}
Using it now like:
switch (bookTypeId) {
case 1:
bookTypeName = MYConstants.BookType.FANTASY.getType();
break;
case 2:
bookTypeName = MYConstants.BookType.HORROR.getType();
break;
case 3:
bookTypeName = MYConstants.BookType.ACTION.getType();
break;
default:
bookTypeName = MYConstants.BookType.ERROR.getType();
}
I want to take this one step further, and clean up my main class of this switch statement (which is sort of why I started looking at enums because right now it seems to do the same thing).
Is it possible to move this switch/case inside of the enum? And then use the enum in a way such as
bookTypeName = MYConstants.BookType.getType(bookTypeId);
Also is it also possible to declare this enum using final (which it currently is complaining about when I try), or is it already final?
Thanks!
MYConstants, instead of stand-alone?Classwould work better in this situation.