Java optional question, did I do this?
I have a "bad habit" of throwing zeros somewhere, such as enumerator 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 > as everyone suggests, but I'm not sure I did it correctly
This is my code (trimmed enumeration):
public static enum Difficulty { EASY,MEDIUM,HARD } public static enum SlayerTasks { NONE(0,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 bothers me is that the document pointing to #get () finds here, which states:
So, I thought I'd wrap getters in #ispresent () to prevent this, but then I couldn't figure out how to return null
Is this the right way to do things, or am I missing something? I'm not looking for "fix", I'm looking for information about efficiency and correct practice
Solution
If there is nothing to return, you need to ask yourself what you want your inhaler to do
There are actually only four options:
>Return null (but you will return to the one you want to avoid); > Let your getter return an optional < T > instead of T; > If it is not set, the default value will be returned; > Throw an exception
Unless I have a very clear and correct answer to what the default should be, I will choose 2 4 it applies only when the client code should always know if something exists, and only asks if it is needed (which is unusual, but not impossible)