Wednesday, April 13, 2011

Null-safe Type in Java 7: New way to handle NullPointerException

Have you ever had an NPE or Null Pointer Exception in production? Or felt that handling null is a right pain? Well perhaps this Java 7 language change proposal - Null-ignore invocation - will interest you.
Though we can take pain, like checking whether that value is null and then further doing checks to ensure all sorts of ways to handle NPE, Java is offering "null safe method invocation" to handle the same.
This operator is ?.
Consider the following code:
Eg. Consider the following code:
public String getName(Person person) {
return person.getName()
}


Now if person is null we will get NPE. So to avoid it we have to check :

public String getPostcode(Person person) {
if(person!=null)
return person.getName();
else return String.Empty;
}


or you may return null to say that person is null. But empty string preferred.

Till this level its fine, suppose you have to use nesting of 2 getters, like:

public String getGrandFatherName(Person person) {
return person.getFather().getFather()
}



So here you have to check 2 times for null:

public String getGrandFatherName(Person person) {
if (person != null) {
Person father = person.getFather();
if (father != null) {
Person grandFather = father.getFather;
if(grandFather != null)
return grandFather.getName();
}
}
return null;
}



So rather than handling these complications, we can get away with ?. operator.

return person?.getFather()?.getFather()?.getName();



This code is null-safe and won't throw NPE. But the main improvement is readability of code.

So what does "?." does?

This proposal aims to tackle this by adding compiler syntax sugar to generate the null pointer checks for developers. It achieves this by adding an alternative to the dot for method and field invocation - ?. Using this invokes a method or field in the same way as using the dot, but with one change. If the expression on the left hand side of the hash is null, then the result of the expression is null. If the expression type is a primitive then zero or false is returned instead of null. If the expression is a void, then no action occurs. 

Refer java complete reference for more on java :

 

No comments:

Post a Comment

Chitika