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?
Null Object pattern. Look at Optional class from google-guava library.
Their wiki has an article on using and avoiding nulls.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With