Suppose you have a method
public void logRequest(Integer userID, String content){
//log content locally or in db or a rest call
}
Suppose you obtain the userID
from database for a particular user. There can be following possibilities:
- DB returns a userID.
- No id found.
So now if no id was found, what do you pass to logRequest
?
- Do you pass
null
? What if the method didnt have appropriate null check. What should it infer null
to?
- Should you pass
0
or -1
? If null
means 0
then it might contradict with an actual user whose ID is 0
. How do you distinguish null and 0?
Of-course the above problem can be solved by proper documentation and fixing the rules, but it gives rise to higher maintenance and is error prone. And properly written code should be its own documentation.
Now say the method was declared as:
public void logRequest(OptionalInt userID, String content)
The method itself makes it very clear that it expects an argument which is optional. So there are only 2 case to handle: An appropriate argument is sent (which means no-bypassing by using 0
). If the optional was empty, then method rightly knows how to handle. (Unlike before where we had to read its documentation to predict the behavior).
So the method declaration it self makes it clear on the behavior rather than documentation doing it for you and relying on documentation and wild-guessing. Optionals are quite useful in such scenarios.
PS: I always feel a pinch passing null
to a method expecting an Integer
. It definitely feels wrong! Gosh, in Java the sub-conscious mind always treats ints as primitives. They are not meant to be nulled.