Beez..
12
鉴于:
public enum PersonType {
COOL_GUY(1),
JERK(2);
private final int typeId;
private PersonType(int typeId) {
this.typeId = typeId;
}
public final int getTypeId() {
return typeId;
}
public static PersonType findByTypeId(int typeId) {
for (PersonType type : values()) {
if (type.typeId == typeId) {
return type;
}
}
return null;
}
}
对我来说,这通常与数据库中的查找表一致(仅适用于很少更新的表).
但是,当我尝试findByTypeId在switch语句中使用时(很可能是用户输入)......
int userInput = 3;
PersonType personType = PersonType.findByTypeId(userInput);
switch(personType) {
case COOL_GUY:
// Do things only a cool guy would do.
break;
case JERK:
// Push back. Don't enable him.
break;
default:
// I don't know or care what to do with this mess.
}
......正如其他人所说,这导致了NPE @ switch(personType) {.我开始实现的一种解决方法(即"解决方案")是添加一种UNKNOWN(-1)类型.
public enum PersonType {
UNKNOWN(-1),
COOL_GUY(1),
JERK(2);
...
public static PersonType findByTypeId(int id) {
...
return UNKNOWN;
}
}
现在,您不必在重要位置进行空值检查,您可以选择或不选择处理UNKNOWN类型.(注意:-1在业务场景中是一个不太可能的标识符,但显然选择对您的用例有意义的东西).
`UNKNOWN`是我见过的最好的解决方案,并且过度使用了nullchecks. (2认同)