Suppose you have a method
public void logRequest(Integer userID, String content){
Suppose you got the userID from the database for a specific user. The following options are possible:
- DB returns the user id.
- Identifier not found.
So, if the id was not found, what do you go to logRequest ?
- Are you
null ? What if the method does not have a null check. What should he do null ? - Do you have to pass
0 or -1 ? If null means 0 , then this may conflict with the actual user with id 0 . How do you distinguish between null and 0?
Of course, the above problem can be solved by correct documentation and correcting the rules, but this leads to higher service and error pricing. And correctly written code should be its own documentation.
Now let's say that the method was declared as:
public void logRequest(OptionalInt userID, String content)
This method shows very clearly that it expects an argument, which is optional. Thus, only 2 cases are processed: the corresponding argument is sent (which means that there is no traversal with 0 ). If the option was empty, then the method correctly knows how to handle it. (Unlike where we had to read its documentation to predict behavior).
Thus, in the method declaration, he himself explains the behavior, not the documentation that performs it for you, and relies on documentation and wild crap. Options in this case are very useful.
PS: I always feel a pinch go null to a method waiting for Integer . This is definitely not the case! Gosh, in Java, the subconscious mind always sees ints as primitives. They should not be null.
source share