How to prevent null checks from your code!!

Today we are going to discuss how to remove or prevent null checks from your code which actually looks ugly in code. To remove these kinds of check we are going to use one library which is provided by apache commons to help you, especially when you are dealing with null objects.

Firstly, we will go through one problem then we will see why we need this library to resolve these types of issues or problems.

As we can see in the above example, the list is assigned with null so when we tried to perform any operation on that list we got NullPointerException which is correct behavior as well in case of null but we should always handle these kinds of scenarios very gracefully and beautifully. So, we will see how we can handle these scenarios gracefully by using apache commons.

So, as we can see in the above example we handled the NullPointerException very gracefully with the CollectionUtils which is provided by apache commons.

Now, we will take one more scenario where you are calling one function which is returning a List<//something> then after taking that value from that function you are doing any computation by using that list. So, suppose the list is coming null to you and you are performing some computation logic, then it is obvious you will get the NullPointerException which we need to handle to cover all scenarios because we are not sure that function will always give the list with values.

Now, we will go one step deeper where what we are going to check is if the given list or any collection is not null but one of its value is null. So, how to handle that case as well which occurs in real life scenarios very usually.

Note: We will handle this case with the ObjectUtils which is also provided by apache commons.

We can see the above example where we are getting NullPointerException while performing some operations on given collection values. So, this is the time to see how we can remove or fix this problem in a mannered way.

As we can see in the above example we handled that NullPointerException case with the help of ObjectUtils class and in a very beautiful way.

I hope this blog was valuable, and you have gained an understanding of how to prevent and handle null checks in code.


Written by 

Kunal Sethi is a Software Consultant with experience of more than 1.5 years. He is a Java enthusiast and has the knowledge of various programming languages such as Scala, C++. He is familiar with Object Oriented Programming Paradigms, love to code applications in J2EE. He developed his own stand alone application in Java based on intranet chating System and email system during his Master's Degree.

Leave a Reply

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!