Joe
Joe

Reputation: 8042

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?

Upvotes: 11

Views: 2860

Answers (8)

Aditya W
Aditya W

Reputation: 662

You don't have to use any design pattern.

Just initialize variables during declaration.

e.g.

List<String> names = new ArrayList<String>();
Map<String,String> pairs = new HashMap<String,String>();

Upvotes: 1

Aravind Yarram
Aravind Yarram

Reputation: 80186

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

Their wiki has an article on using and avoiding nulls.

Upvotes: 11

Parker
Parker

Reputation: 7519

These methods (see also Apache commons-lang) can reduce the burden of null checks in the cases of String processing by encapsulating them in methods that preserve semantic meaning of code:

public static boolean isBlank(final String str)
{
    return (str == null) || str.isEmpty();
}

public static boolean isNotBlank(final String str)
{
    return !StringUtils.isBlank(str);
}

public static boolean isEqual(final String s1, final String s2)
{
    if (s1 == s2) { return true; }
    if ((s1 == null) || (s2 == null)) { return false; }
    return s1.equals(s2);
}

public static boolean isNotEqual(final String s1, final String s2)
{
    return !StringUtils.isEqual(s1, s2);
}

Upvotes: 1

Irina
Irina

Reputation: 51

"something definetly not null".equals(maybeNullVar)

vs

maybeNullVar.equals("something definetly not null")

Upvotes: 2

Irina
Irina

Reputation: 51

There are some helpfull annotations designed for thiese purposes by IntellyJ: @Nullable and @NotNull
Detecting probable NPE’s

Upvotes: 3

UmNyobe
UmNyobe

Reputation: 22890

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.

Upvotes: 3

Marcelo
Marcelo

Reputation: 4608

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.

Upvotes: 3

pap
pap

Reputation: 27614

I guess it's a matter of taste, but I would say that the greatest banes of languages like Smalltalk/Objective-C is that they DON'T have null and that there AREN'T any NullPointerExceptions. I'm not a fan of "Null object pattern", in fact I detest it with passion as I find it makes troubleshooting and finding bugs so much harder without any real benefit. Null has a meaning (often bad) and should not be treated like any other generic state.

Like has been mentioned in this thread, NPE are really powerful and a good way to catch syntactical errors or bad coding early on and if (obj != null) is pretty straight-forward. If your application starts generating NPE at runtime, you've done something wrong and you need to fix it. Don't try to hide the exception, fix whatever it is that is CAUSING the exception.

Upvotes: 2

Related Questions