【发布时间】:2014-11-24 10:20:53
【问题描述】:
我有一个“坏习惯”,即在某些地方不存在时将null 扔到诸如枚举器之类的地方。
例子:
private enum Foo {
NULL(1, null, 2),
NOT_NULL(3, new Bar(), 4);
private int a, c;
private Bar b;
Foo(int a, Bar b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
所以现在我正在尝试将我的代码转换为使用Optional<T> 就像每个人都建议的那样,但我不确定我是否正确地做。
这是我的代码(修剪过的枚举):
public static enum Difficulty {
EASY, MEDIUM, HARD
}
public static enum SlayerTasks {
NONE(0, Optional.empty(), Optional.empty(), Optional.empty()),
NPC(1, Optional.of(Difficulty.EASY), Optional.of("That one place."), Optional.of(1));
private int taskId;
private Optional<Difficulty> difficulty;
private Optional<String> location;
private Optional<Integer> npcId;
SlayerTasks(int taskId, Optional<Difficulty> difficulty, Optional<String> location, Optional<Integer> npcId) {
this.taskId = taskId;
this.difficulty = difficulty;
this.location = location;
this.npcId = npcId;
}
public int getTaskId() {
return taskId;
}
public Difficulty getDifficulty() {
return difficulty.get();
}
public String getLocation() {
return location.get();
}
public int getNpcId() {
return npcId.get();
}
}
困扰我的是在here 找到的引用#get() 的文档,其中指出:
如果此 Optional 中存在值,则返回该值,否则抛出 NoSuchElementException。
所以,我想为了防止这种情况,我会将 getter 包装在 #isPresent() 中,但后来我不知道如何返回空。
这是正确的做事方式,还是我错过了什么?我不是在寻找“修复”,而是在寻找有关效率和正确做法的信息。
【问题讨论】:
-
如果你调用 Optional.get() 你可能做得不对。