Tag Archives: nullpointerexception

Guidelines to avoid null check statements

If you are tired of seeing NullPointer Exception, you are not alone. In this post, I show some guidelines to avoid null check. Have you ever seen code like below?

Object obj = anotherobj.getObject();
if(obj != null)
{
    // do something with obj
}

Imagine if you have to write such if-statement block for every object or variable you retrieve from different contract objects in your code, it would make the code cumbersome and unreadable. Also, it gives an impression of the naivety of developers in such cases.

I am writing this post based on a heavy discussion happening on StackOverflow Avoiding Null Statements. I am only using this post as a reference and writing my own guidelines based on my own experience. Answers to that post on StackOverflow are worth to checkout.

Guidelines to avoid checking null statements

  1. If callee keeps a contract of never returning a null, then the caller doesn’t have to add any check statement for a null value. But this is the basic premise a developer should follow when writing methods.
  2. Most of the time, the issue is not method returning null, but the logic implemented in these methods is not accurate. If the business logic of a method knows a way to handle errors in cases when it can return the right data, it should return an error instead of returning null.
public String getEmployeeInformation(String empcode)
{
   if (empcode == null)
   {
     // instead of returning null, throw an error
      throw new IllegalArgumentException(" empcode is null ");
   }
}

3.  Java 8 offers a new keyword optional 

public Optional<Employee> getEmployeeInfoWithSSN(String ssn) 
{ 
  .............. 
}

 

So if the employee information with particular SSN is not found, then the caller of this method has to explicitly think about the type system.

4.  Intellij Idea offers Java annotations like `Nullable` and `NotNull` 

5.  Write junit test cases for your classes which check for `assertNotNull()`

6.  Java 7 offers a utility method for Objects , Objects.requireNonNull();

Conclusion

In this post, I showed guidelines to avoid null check. Once you use these strategies, you make your life as a programmer way easier.

References

  1. Avoid null check statements
  2. Optional keyword