Can I null-check in-line?

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.

Answers


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.


Need Your Help

Count occurrences of CSS classes

html css ruby nokogiri

I have a Ruby program that takes as input an HTML document. The structure of this HTML document is unknown and can really be anything.

How to use sub queries while inserting record into db using cx_Oracle in python?

python oracle python-2.7

I need to add a symbol with the value of self.wrkArea variable like this

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.