Thursday, November 7, 2013

Prevention is better than cure (Preventing NPE without null check)

As I mentioned on my previous blog post, NPE (Null Pointer Exception) is the most common exception in java. But if you are having enough attention on to your code, you can easily avoid most of the possibilities of getting NPE. The easiest cure, probably the most common cure for NPE is checking null values whenever there is a doubt. Check follows extreme case.

This works fine, but is this cute? Unarguably this is not the best way to prevent NPE. Think twice, why we do not trust the values return by the bean accessors? If we trust them our code will be like this.

How we can achieve this?
It is not that much hard to archive this. Most of the developers think the sole usage of mutator method is to change the value of the variable. But it is not, check follow bean.

Now we can guarantee, no accessor method will return a null value. Still we are getting an exception (IllegalArgumentException) but keep in mind it is good to getting exception early as possible and here we know the exact reason for getting the exception.

No comments:

Post a Comment