Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are good light-weight design patterns for avoid nulls in Java?

Obviously one of the greatest banes of Java programming is nulls and null-pointer exception. What design patterns are there that don't add too much to your code but reduce the problem of sand null-pointer exceptions?

like image 489
Joe Avatar asked Feb 06 '12 15:02

Joe


3 Answers

Null Object pattern. Look at Optional class from google-guava library.

Their wiki has an article on using and avoiding nulls.

like image 90
Aravind Yarram Avatar answered Nov 16 '22 07:11

Aravind Yarram


Just get used to not returning null objects on your methods.

public MyObject bohemianRhapsody(){

   try {
       if(isThisTheRealLife())
           return new MyObject("is this just fantasy");
       else
           return new MyObject("caught in a landslide, no escape from reality");
   } catch(ExampleCatchableException e){
       return new MyObject(""); // instead of return null
   }
}

...
System.out.println(bohemianRhapsody()); // will never print null

Also (kind of) referred to as the Null-Object pattern.

like image 38
Marcelo Avatar answered Nov 16 '22 07:11

Marcelo


Why do you want to avoid null pointer exception? Getting null when expecting something else it is one of the first indications something is wrong when you write code. Things like Null Object Pattern should be use when you are sure it is adequate. One of the biggest disadvantages of design pattern are their abuse\misuse.

EDIT:

I think the best way to reduce null return will be to increase usage of exceptions. Think about a List returning a null object when you try to access to the element at index -1, you will be using things like

if( list.get(-1).equals(nullObject))

which is even worse. I believe it is better to raise an exception when the arguments are either unexpected or incompatibles.

like image 3
UmNyobe Avatar answered Nov 16 '22 06:11

UmNyobe