拒绝 ! = null



1、假如方法的返回类型是collections,当返回结果是空时,你可以返回一个空的collections(empty list),而不要返回null,这样调用侧就能大胆地处理这个返回,例如调用侧拿到返回后,可以直接print list.size(),又无需担心空指针问题。
(什么?想调用这个方法时,不记得之前实现该方法有没按照这个原则?所以说,代码习惯很重要!如果你养成习惯,都是这样写代码(返回空collections而不返回null),你调用自己写的方法时,就能大胆地忽略判空)
if (CollectionUtils.isEmpty(ids)) {
return Collections.EMPTY_LIST;
}





2、返回类型不是collections,又怎么办呢?那就返回一个空对象(而非null对象),下面举个“栗子”,假设有如下代码:
public interface Action {
  void doSomething();}

public interface Parser {
  Action findAction(String userInput);}
其中,Parse有一个接口FindAction,这个接口会依据用户的输入,找到并执行对应的动作。假如用户输入不对,可能就找不到对应的动作(Action),因此findAction就会返回null,接下来action调用doSomething方法时,就会出现空指针。解决这个问题的一个方式,就是使用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的方法。
posted @ 2021-05-31 17:49  风骚羊肉串  阅读(51)  评论(0编辑  收藏  举报