Monday, August 4, 2014

[JAVA] Evil Null

Elvis operator could have been a good use here. But unfortunately have been decline till now.

Its used to say "?." Operate only if not null.

Class A
 public B getB()
   return new B();

public void test( A a)
    if ( a != null  )
        return a.getB();

Above method would be replaced with

public void test ( A a)
     return a?.getB();

Unfortunately its still some time we can see some think like that. So till that we have to live with two choices:

1. Check for null.
2. Use the Null Object Pattern.

So we all know that how to check for null objects and believe me i had real long chain of checking null.

Second way can be useful but if this chain is pretty long its can be tiresome to have null object for all the hierarchy

Null Object means there will be definition of class A (mostly derived from same interface.) and will have dummy methods which will nullify any call to these methods.

No comments:

Post a Comment