如何避免判空(!=null)语句

原文链接 Avoiding != null statements

在StackOverFlow上,看到了对判空语句的讨论。
Best votes 的答题者认为 初、中级程序员喜欢在方法中返回null,因此在调用这些方法中不得不去判空。这样,在他们潜意识中为了保护自己的代码就会加入大量的判空语句,这是不好的。

程序中出现null有如下两种情况:

  1. null是一个有意义的返回值 (比如在方法中返回null,作为一种情况的标示)
  2. null是一个异常

对于第二种情况,Best votes 的答题者给出如下两种解决方法:

  1. assert语句,可以将设定的错误原因放到assert的参数中,这样当程序异常时,可以返回错误且程序不会往下走。( 在开发中使用assert不推荐,更多的应该用在unit test 中。参照Java陷阱之assert关键字 )
  2. 抛出空指针异常

对于第一种情况,就是通过返回空对象替代返回null.

1 对于数组或集合,应该返回零长度的数组或集合

//The right way to return an array from a collection
private final List<Cheese> cheesesInStock = ...;
private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];

public Cheese[] getCheeses(){
    return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
}

//The right way to return a copy of a collection
public List<Cheese> getCheeseList(){
    if(cheesesInStock.isEmpty())
        return Collections.emptyList();
    else
        return new ArrayList<Cheese>(cheesesInStock); 
}

2 对于返回类型不是数组或集合,那就返回空对象。实例如下:

public interface Action {  
  void doSomething();}  

public interface Parser {  
  Action findAction(String userInput);} 
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;  
    }  
}}  

判空的写法:

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();
}  

精简写法(空对象模式):

ParserFactory.getParser().findAction(someInput).doSomething();  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值