3 ms·
I am not sure I understand. I guess you are either saying (A) to treat every return type as possibly null or (B) to use your judgment when doing null checks of
by w23j 11y ago
I am not sure I understand.
I guess you are either saying (A) to treat every return type as possibly null or (B) to use your judgment when doing null checks of return types.
In case of (A):
Do you want to write null-checks for methods like String.toUpperCase() or for user.getLastName()? That would lead to a lot of bloated, dead code. Also do you want to write error handling for all these cases you know can never happen?
In case of (B):
NullPointerExceptions are most likely when the user of an API did not expect he might get a null value. For instance user.getDepartment -> null. "What? An employee does not have to have a department?!" In this case you force users of an API to guess if they might reive a null return value. And they might guess wrong, which either leads to dead code or NPEs. Using Optional as a return type makes the difference explicit.
- MereInterest 11y agoI would say that every return type that can be NULL should be checked for being NULL. In C++, this is possible, because you most functions are return-by-value or return-by-reference. This leaves only return-by-pointer that need to be explicitly checked. In Java, all functions that do not return primitives are return-by-pointer, and are therefore nullable. This, as you mentioned, makes it infeasible to apply null-checks on every function return.
- craigching 11y agoA consistent API written with Optional should make it such that if an Optional is returned, then a null value could have been returned. If an Optional is not returned (including for references), then you can assume that null will not be returned. This is a contract that can be documented as part of the API documentation. To me, this is much clearer than having to guess on every call and I would prefer this use of Optional or not in an API to an API without Optional and having to check everything.