I have a method that can return a null value.
Use the return type of Optional to let callers know they need to handle absent values.
In this example the null check is needed because the city code may not exist in the repository.
However, it is not clear from the findCity method that a null could be returned.
When it is possible for a null to be returned from a method use an Optional wrapper class to let the caller know what to expect and that they need to handle the case where the value is absent.
The optional class contains the instance that can be null and offers several convenience methods to elegantly handle the null condition. Java 8 users should use the java.util.Optional version - since it is integrated into the various Java 8 APIs. For other users there is a version in the Google Guava framework.
Refactoring the null check example results in the following new implementation.
No comments:
Post a Comment