简体   繁体   English

Java:快速/优雅的方式来检查null

[英]Java: Quick/Elegant way to check for null

In the program I'm currently writing, I find myself doing the following a lot... 在我正在编写的程序中,我发现自己做了以下很多事情......

Map<String,List<String>> network = loadSerializedObj(file); // null if failed
if(network != null) {
    anonNet = util.anonymize(newNet);
} else {
    // Some sort of error handling.
    System.out.println("Some sort of error message. Exiting...");
    System.exit(0);        
}

Is there a more succinct way of handling the event that loading the serialized object from file doesn't work and the method returns null? 有没有更简洁的方法来处理事件,从文件加载序列化对象不起作用,并且该方法返回null? Any tips at all are welcome. 任何提示都是受欢迎的。 Anywhere I can make this more elegant? 在哪里,我可以让它更优雅?

you should make loadSerializedObj throw an exception instead of return null. 你应该使loadSerializedObj抛出异常而不是返回null。 you can return null when you don't have anything to return. 当你没有任何东西可以返回时,你可以返回null。 when something breaks, you should throw an exception. 什么东西坏了,你应该抛出异常。

In this case you can use the exception catch. 在这种情况下,您可以使用异常catch。

Map<String,List<String>> network = loadSerializedObj(file); // null if failed
try {
    anonNet = util.anonymize(newNet);
} catch(NullPointerException npe) {
    System.out.println("Some sort of error message. Exiting...");
    System.exit(0);        
}

but you must specify the util.anonymize to throw the NullPointerException if it does not it yet. 但是你必须指定util.anonymize来抛出NullPointerException,如果还没有的话。

you could have some kind of 你可以有某种

class MyAssert {
  static<T> assertNotNull(T object) {
    if (object == null) {
      System.out.println("something is wrong...");
      System.exit(0);
    }
    return object;
  }
}

Try returning an empty map instead of a null value: 尝试返回空地图而不是空值:

    if(!loadSerializedObj(file).isEmpty()) 
    {
        anonNet = util.anonymize(newNet);
    } 
    else 
    {
        // error handling    
    }

    private Map<String,List<String>> loadSerializedObj(File file) 
    {
        // do stuff
        if(mapObject == null)
        {
            mapObject = Collections.emptyMap();
        }
        return mapObject
    }

You could do a static import of a function named n(object) that returns boolean if null. 您可以对名为n(object)的函数进行静态导入,如果为null,则返回boolean。 Or use Groovy :) 或者使用Groovy :)

我认为你所拥有的是在保持易于阅读/维护代码的同时获得的。

番石榴的先决条件可以是一个简洁易读的检查方法。

Preconditions.checkNotNull(myReference, "My error message");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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