Friday, 7 September 2018

Your Java method should warn about NPE while coding itself

Define your method is such way that, any IDE or Static Code Analyzer can sense the billion-dollar mistake, aka NullPointerException while writing the code to call the method.

Here are some best practices while defining a new Java method. 
  • Method should have clear documentation with
    • Purpose of the method
    • Parameters of the method – Mark the parameter with @javax.annotation.Nonnull if null is not expected
    • Return type of the method – Mark the return type with @javax.annotation.Nullable if it can be null
* This method filters product from the productList by supplied productId and type and return the same. 
* If no match found then returns null. 
* @param productId a non-null product ID for which the filter is requested
* @param type a non-null type value for which the filter is requested
* @return Product if found the match by productId and type else return null 
public @Nullable Product filterProductByIdAndType(@Nonnull BigInteger productId, @Nonnull Character type) {
   Product product = null;
   for (Product eachProduct : productList) {
      if (productId.equals(eachProduct.getId()) && type.equals(eachProduct.getType())) {
         product = eachProduct;
   return product;

How it helps while calling the method?
  1. It warns that the argument might be null while the method is expecting a Nonnull parameter.  In this case productId may be null because the assignment is conditional.
  1. It also warns about the NPE because there is a possibility of getting Null from the method. In this case the method can return null as per the method documentation.
Let’s follow these best practices to avoid nightmares.