简体   繁体   中英

Is there a simpler way to derefence nullable references in Java?

Consider the following Code Snippet:

if (foo != null
 && foo.bar != null
 && foo.bar.boo != null
 && foo.bar.boo.far != null)
{
    doSomething (foo.bar.boo.far);
}

My question is simple: is there a more simple\\shorter way to do this ?

In detail: is there a more simple way to validate each part of the chain, I'd imagine similar to this ..

if (validate("foo.bar.boo.far"))
{
    doSomething (foo.bar.boo.far);
}

Maybe like that ?

if (FooUtils.isFarNotEmpty(foo)){
    doSomething (foo.bar.boo.far);
}

and in FooUtils :

boolean isFarNotEmpty (Foo foo){
   return foo != null && 
          foo.bar != null && 
          foo.bar.boo != null && 
          foo.bar.boo.far != null;
}

在我看来,这个表达是完美的,没有什么可以更简单

为什么要使用公共实例变量,封装公共变量并为它们创建getter和setter,并且可以在getter中执行这些检查,如果其中任何一个为null,则可以返回新的Object(),或者可以运行此语句在try-catch块中,但不推荐,

If this is your API please consider some advice .

"I call it my billion-dollar mistake." - Sir CAR Hoare, on his invention of the null reference

There's not much you can do with this, unfortunately. If you ask me, it's a problem with the Java language. Groovy has something called the Safe Navigation Operator ?. that is specifically for this purpose. Here are two things I've done in the past.

  1. The answer that Grisha already gave, so I won't repeat it
  2. Naively wrote code that accesses it, and surround it in a try/catch for a NPE. Here's an example:

     try { if (foo.bar.boo.far != null) { //do something } } catch (NullPointerException e) { //do what you would do in an else } 

I don't particularly like the 2nd option, but I say if it actually makes the code cleaner, consider using it.

One time I was working with a library that is a very thin wrapper over an XML schema and I decided to use the 2nd option for this case. If I didn't, the code would have been harder to maintain because it would be so easy to forget a null check and they cluttered up the important logic. I think that's a valid case for using it.

Please try this code

try {
    if (foo.bar.boo.far != null) {
        //No object is null
    }
} catch (Exception e) {
    // some object is null and causes null point exception.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM