进行判空前,请区分以下两种情况:
1、 null 是一个有效有意义的返回值(Where null is a valid response in terms of the contract; and)
2、 null是无效有误的(Where it isn’t a valid response.)
你可能还不明白这两句话的意思,不急,继续往下看,接下来将详细讨论这两种情况
先说第2种情况
1、 assert语句,你可以把错误原因放到assert的参数中,这样不仅能保护你的程序不往下走,而且还能把错误原因返回给调用方,岂不是一举两得。(介绍了assert的使用,这里省略)
2、 也可以直接抛出空指针异常。上面说了,此时null是个不合理的参数,有问题就是有问题,就应该大大方方往外抛。
第1种情况会更复杂一些
这种情况下,null是个”看上去“合理的值,例如,我查询数据库,某个查询条件下,就是没有对应值,此时null算是表达了“空”的概念。
那就返回一个空对象(而非null对象),下面举个“栗子”,假设有如下代码
public interface Action {
void doSomething();}
public interface Parser {
Action findAction(String userInput);}
解决这个问题的一个方式,就是使用Null Object pattern(空对象模式)。
类定义如下,这样定义findAction方法后,确保无论用户输入什么,都不会返回null对象
public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// …
if ( /* we can’t find any actions */ ) {
return DO_NOTHING;
}
}
}
对比下面两份调用实例
1、 冗余:每获取一个对象,就判一次空
Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn’t (or shouldn’t be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing} else {
action.doSomething();}
2、 精简
ParserFactory.getParser().findAction(someInput).doSomething();
因为无论什么情况,都不会返回空对象,因此通过findAction拿到action后,可以放心地调用action的方法。避免空指针的 5 个案例推荐看下。
其他回答精选
1、 如果要用equal方法,请用object<不可能为空>.equal(object<可能为空>))