I've had a "Bad habit" of tossing null
into places, such as enumerators when something doesn't exist.
Example:
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;
}
}
So now I'm trying to convert my code to use Optional<T>
Like everyone is suggesting, but I'm not sure if I'm doing it correctly.
Here's my code (Trimmed enum):
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();
}
}
What's bothering me is the documentation referring to #get()
found here where it states:
If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
So, I figured that in order to prevent this I would wrap the getter in #isPresent()
, but then I couldn't figure out how to return empty.
Is this the correct way to do things, or am I missing something? I'm not looking for a "Fix", I'm looking for information on efficiency and proper practices.