Avoiding "!=null" comparison in Java

Question:

I work with Java and countless times I have to do an object != null test on the object before accessing it to avoid NullPointerException

However, I think that this practice ends up making the code very ugly, dirty and difficult to read.

Is there any alternative to avoid this comparison every time I want to access an object's method?

For example:

System.out.println("Nome: " + pessoa.getNome());

To be safe it becomes:

if (pessoa!=null) {
    System.out.println("Nome: " + pessoa.getNome());
}

Answer:

What style of code to use?

There are two types of programming we can use: contract or defensive.

  • Contract programming is something harder to find out there. It preaches that one should see what the method expects, what the documentation says to use and follow. Developer problem if you don't follow these rules. Errors will happen but that doesn't matter, he didn't send the data right. How does this affect the code? You wouldn't need to validate the attributes received and simply let the error pop. The problem with this approach is the many runtime errors that will appear and also the constant need for detailed and up-to-date documentation.
  • Defensive programming, on the other hand, says that you must validate everything that is important to the called method. Validate from simple attributes ( String , int , etc) as objects of your model (House, Car, etc). The downside to this is that you will always have an extra if in your code for validation.

What can I do to validate?

You can use several techniques to validate an attribute:

  • Use code-shortening libraries. ApacheCommons, for example, has several classes that facilitate validation. I can quote StringUtils.isBlank(texto) to validate if the text is empty or not. And the interesting thing is that to make the code easier to read, they created the isNotBlank(texto) method which is the negation.
  • Use JSR 303: Bean Validation. It is the data validation specification. Just annotate it with a @NotNull and you're done. Take a look at Hibernate Validator.
  • Make an IF on the nail. This is a very simple solution, but as said, it makes the code bigger. The best thing would be to isolate this code in a separate method.
  • Use assert. I don't recommend this one and to tell you the truth, no one recommends using assert in production. It kills the thread that invoked the method.

Conclusion

For this type of situation there is no perfect solution, but there are alternatives that help in the development of cleaner code.

Scroll to Top