Skip to content

How to avoid “!= null” statements in Java?

January 28, 2010

One of the common problems that most developers tend to face at some point is defensively over checking for nulls. Many anticipate the null response without trusting the contract and bloat the code with !=null conditions making it unreadable and ugly.  Often times a method needs to return a value or nothing depending on its internal and working state.  Here nothing includes the null value too which means returning a null value is a valid one by contract.

To be precise, we have two options in getting the response

i. null is not allowed

ii. null is allowed

option i is easy to handle. If null  is not allowed,

Use assert and throw an error stating it. The JRE is configured by default to ignore the asserts. By using the option -esa (enablesystemassertions), one can enable asserts to various levels like classes or packages.

option ii – null is allowed and if it is passed from external method, then one have to be careful in dealing with it. You have no choice other than using

if( value !=null)

doSomething()

else

doOtherthing();

Its one time checking. You are sure that value cannot be null for the rest of the program and you are free to use the variable in subsequent methods without any block to check for null conditions.

On the other way, if you have control over the external method, then you can force the method to return empty string or empty collections instead of null as described in NULL OBJECT pattern.

The Null Object says,  “Just because I don’t have anything and don’t do anything, it does not mean that I am not smart.  By not having anything, I don’t take up much resource and can be shared among many.  By not doing anything, I am doing the right thing.”



Martin Fowler claims Nulls are awkward things and comes up with this particular refactoring pattern.

“Instead of returning null, or some odd value, return a Special Case that has the same interface as what the caller expects.”

Java has proposed for the null type annotation in JSR 305 and the proposal has some contradictions  described here.

Null-ignore invocation and Null safe types are another proposals similar in some ways to the JSR 305/308 annotation proposal for annotating whether parameters may or may not be null.

Proposals can be viewed at  Null-ignore invocation, Null-safe types

Null-ignore invocation is concerned with dealing with possible null values in calling one or especially a chain of methods.

For example, instead of

public String getPostcode(Person person) {
if (person != null) {
Address address = person.getAddress();
if (address != null) {
return address.getPostcode();
}
}
return null;
}

you could instead call:

public String getPostcode(Person person) {
return person?.getAddress()?.getPostcode();
}

Another issue concerns how to handle common if-null scenarios with a shortened form of the ternary operator specific to nulls. So rather than:

String str = getStringMayBeNull();
str = (str == null ? “” : str);

you might do:

String str = getStringMayBeNull() ?: “”;

This proposal moves checking of nulls from run-time to compile-time which will avoid many NullPointerExceptions and increase the robustness of Java programs.

About these ads
15 Comments leave one →
  1. January 29, 2010 7:43 am

    Alternatively, import the FunctionalJava library and use the Option monad. That way, you explicitly state “this may be null” until you ‘unwrap’ the Option.

    • abi permalink*
      January 29, 2010 8:44 am

      thanks for sharing it.I haven’t used it yet. will try with that soon.

  2. January 29, 2010 11:24 am

    +1 for the Optional pattern / Option monad. That realy clearifies an api:

    public Optional getOptionalString(); // or public Some …
    String s = getOptionalString().hasValue()
    ? getOptionalString().getValue()
    : “”;

    Makes your code documented.

  3. Casper Bang permalink
    January 29, 2010 12:04 pm

    I use a small snippet I think of as the poor Java man’s elvis operator:

    private static T escapeNull(T possibleNullItem, T defaultItemIfNull) {
    if (possibleNullItem == null)
    return defaultItemIfNull;
    return possibleNullItem;
    }

    It’s not to be used in “hot code”, since defaultItemIfNull is used/calculated unconditionally. However it reads rather nicely in code, where you otherwise can’t use the null pattern (escaping null coming from a database etc.).

  4. January 29, 2010 12:45 pm

    @Trent: Of course you could use the Option monad.

    Option x = …
    if(x instanceof Some) {
    System.out.println(x.get());
    } else if(x instanceof None) {
    System.out.println(“invalid”);
    }

    But using ‘instanceof’ instead of ‘!= null’ is just as bad and also expensive. Furthermore null is still a possible return value. I already mentioned that at my post “Confused by the Option Pattern for a Better Nullpointer Handling in Java” (http://www.devpg.com/confused-by-the-option-pattern-for-a-better-nullpointer-handling-in-java)

    Best regards!

  5. January 29, 2010 7:35 pm

    I believe it worth noting that Groovy allows for such syntax.

    http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28%3F.%29

    They call it the SafeNavigationOperator.Its purpose is used to avoid NPE’s.

  6. January 29, 2010 9:09 pm

    I agree with these thoughts! The overreaching best practice here is to “Never Return Null!”

    Nulls are poison in complex applications. Code-size and cyclomatic complexity explode when you lace your logic with “null != var”.

    Throw an unchecked exception before you return null.

    • abi permalink*
      January 30, 2010 9:36 am

      Lincoln,

      “Throw an unchecked exception before you return null” — is one of the best practices. Thanks for adding it.

  7. Jimmy permalink
    February 9, 2010 7:08 pm

    I have to disagree with how the last part is stated, about:

    String str = getStringMayBeNull() ?: “”;

    moving the checking of null from run-time to compile-time. Unless there’s something I’m missing, this is really the compiler giving you some help in writing the code for the null check. The null check itself is still done at run-time. If the compiler determined code paths where getStringMayBeNull() would either always or never be null, and skipped generating the code for the run-time check in those cases, that would be checking at compile-time instead of run-time.

    Also, for my two cents, I’m not sure the syntactic sugar for eliminating the null checks, such as null-default and null-safe invocation, is worth while. It makes the code marginally easier to write at the expense of making it harder. I think you’re better off with the readability.

    The null-safe types feature I think is a good idea however, as it adds more compile-time verification.

  8. February 19, 2010 9:02 am

    I’ve posted some ideas around the Null object pattern’s applicability specifically for JPA Entities (ORM) at http://www.vorburger.ch/blog1/2009/11/jpa-idobject-references-always-with.html. And thanks for various interesting links above; I’ve put together http://delicious.com/vorburger/null+java as a summary.

  9. April 21, 2010 8:07 am

    very informative..thanks a lot..james
    javajobs.net

Trackbacks

  1. Tweets that mention How to avoid “!= null” statements in Java? « Technical Jottings -- Topsy.com
  2. Avoid Quit Smoking Cold Turkey Side Effects If You Quit Via NLP |
  3. Quit Smoking TODAY To Avoid the Dangers! |

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: