Can I null-check in-line?

47,958

Solution 1

I think you remember the elvis operator ( http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000047.html ) which was rejected ( https://blogs.oracle.com/darcy/entry/project_coin_final_five ) from project coin.

However, the jakarta commons have nvl-like functions such as http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/StringUtils.html#defaultString(java.lang.String) Even though these functions are not standard java, they end up in most programs as dependecy of some library.

The problem you have is a common when you design a function with a valid null result: You have to document and handle the special case everywhere. I can pretty much guarantee you that someone will mess this up in maintenance, resulting in spurious null pointer exceptions. That's why i would, in general, recommend designs that don't return null.

Solution 2

With the ternary operator :

String string = bs != null ? f.format(bs) : "";

Solution 3

I'm late to the game but I wanted something similar and found use of Java 8 Optional class. Solution for problem statement in question:

String string = Optional.ofNullable(bs).map(f::format).orElse("");

Solution 4

Another way with the ternary operator:

String string = bs == null ? "" : f.format(bs);

Solution 5

not in java, but some JVM based languages ( notable: groovy ) have null safe dereference:

http://groovy.codehaus.org/Null+Object+Pattern

Share:
47,958
Redandwhite
Author by

Redandwhite

Experienced in Java, C#.NET, ASP.NET, HTML, CSS, JS, PHP, MySQL, MSSQL, SSRS. Basics in C, Obj-C. Twitter: @simonsc Blog: Bleached Bits

Updated on November 30, 2020

Comments

  • Redandwhite
    Redandwhite over 3 years

    I have a Java command that looks something like below:

    Foo f = new Foo();
    String string = f.format(new Bar().getSelection());
                           // ^ may be null
    

    Sometimes it's possible that my Bar object returns null, this is by design.

    To me, the natural thing to do is to split the commands into multiple lines and do a null-check separately, such as:

    Foo f = new Foo();
    BarSel bs = new Bar().getSelection();
    String string = "";
    if (bs != null) {
        string = f.format(bs);
        // continue...
    }
    

    However, I'm wondering if there is a way to do this in one line? Is it possible to null-check objects inline?

    I seem to remember reading about being able to use question mark, but I can't recall the exact syntax and I might be wrong about that. Note that I'm not referring to the ternary operator, although that is another valid approach.