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.
You need to ask yourself what you want your getter to do if there's nothing to return.
There are only really four options:
Optional<T> instead of a T;I'd go with 2 unless there's a very clearly right answer for what the default should be. 4 is appropriate only if the client code should always know whether there's something there and only ask for it if there is (which would be unusual, though not impossible).
You can replace location.get() with location.orElse("SomeDefaultValue") if you wish to avoid the exception. This allows you to return a default value when the Optional is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With