小编典典

java如何避免object != null?

java NullPointerException

object != null要避免很多NullPointerException

有没有好的替代方法?

例如:

if (someobject != null) {
    someobject.doCalc();
}

NullPointerException当不知道对象是否存在时,可以避免使用null


阅读 965

收藏
2020-01-10

共1个答案

小编典典

在我看来,这似乎是一个相当普遍的问题,初级和中级开发人员往往会在某个时候遇到这些问题:他们要么不知道,要么不信任他们所参与的合同,并且防御性地检查了null。另外,在编写自己的代码时,他们倾向于依靠返回空值来表示某些内容,因此要求调用者检查空值。

换句话说,在两种情况下会出现空检查:

  1. 如果为null,则表示合同中的有效回复;
  2. 无效的地方。

(2) 容易。使用assert语句(断言)或允许失败(例如 NullPointerException)。断言是1.4中新增的一个未被充分利用的Java功能。语法为:

assert <condition>

要么

assert <condition> : <object>

where <condition>是一个布尔表达式,<object>是一个对象,其toString()方法的输出将包含在错误中。

一个assert语句抛出一个Error(AssertionError如果条件是不正确的)。默认情况下,Java会忽略断言。你可以通过将选项传递-ea给JVM 来启用断言。你可以启用和禁用单个类和程序包的断言。这意味着尽管我的测试几乎没有显示断言对性能的影响,但是你可以在开发和测试时使用断言来验证代码,并在生产环境中禁用它们。

在这种情况下,不使用断言是可以的,因为代码只会失败,这就是使用断言时会发生的情况。唯一的区别是,有了断言,它可能会更早地发生,以更有意义的方式出现,并可能带有额外的信息,这可以帮助你弄清楚为什么不期望它会发生。

(1)有点难。如果你无法控制正在调用的代码,那么你将陷入困境。如果null为有效响应,则必须检查它。

但是,如果你控制的是代码(通常是这种情况),那就是另一回事了。避免使用null作为响应。使用返回集合的方法很容易:几乎总是返回空集合(或数组)而不是null。

使用非集合,可能会更困难。以这个为例:如果你具有以下接口:

public interface Action {
  void doSomething();
}

public interface Parser {
  Action findAction(String userInput);
}

在Parser中,原始的用户输入会找到要执行的操作,如果你正在为某些操作实现命令行界面的话。现在,如果没有适当的操作,你可以使合同返回null。这导致你正在谈论的空检查。

另一种解决方案是从不返回null,而使用Null Object模式:

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

这是一个更好的设计,因为它可以导致代码更简洁。

也就是说,对于findAction()方法来说,抛出带有有意义的错误消息的Exception异常是完全适当的-特别是在这种情况下,你依赖于用户输入。对于findAction方法抛出一个异常,比对一个没有解释的简单NullPointerException进行抛出的调用方法要好得多。

try {
    ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
    userConsole.err(anfe.getMessage());
}

或者,如果你认为try / catch机制太丑陋,而不是什么都不做,则默认操作应向用户提供反馈。

public Action findAction(final String userInput) {
    /* Code to return requested Action if found */
    return new Action() {
        public void doSomething() {
            userConsole.err("Action not found: " + userInput);
        }
    }
}
2020-01-10