Tag Archives: stackoverflow

Guidelines to avoid null check statements

Have you ever seen a 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 naivety of developer 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 caller doesn’t have to add any check statement for null value. But this is 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 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 caller of this method has to explicitly think about 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();

 

References –

  1. Avoid null check statements
  2. Optional keyword
Advertisements