为什么要使用Objects.requireNonNull()? [英] Why should one use Objects.requireNonNull()?

查看:6922
本文介绍了为什么要使用Objects.requireNonNull()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要使用 Objects.requireNonNull()

Why should one use Objects.requireNonNull() ?

我有注意到Oracle JDK中的许多Java 8方法使用 Objects.requireNonNull(),如果给定的对象在内部抛出 NullPointerException (参数)是 null

I have noted that many Java 8 methods in Oracle JDK use Objects.requireNonNull(), which internally throws NullPointerException if the given object (argument) is null.

public static <T> T requireNonNull(T obj) {
    if (obj == null)
        throw new NullPointerException();
    return obj;
}

NullPointerException 将如果取消引用 null 对象,则无论如何都要抛出。那么,为什么要做这个额外的空检查并抛出
NullPointerException

But NullPointerException will be thrown anyway if a null object is dereferenced. So, why should one do this extra null check and throw NullPointerException?

一个明显的答案(或者好处是它使代码更具可读性,我同意。我很想知道在方法开头使用
Objects.requireNonNull()的任何其他原因。

One obvious answer (or benefit) is that it makes code more readable and I agree. I'm keen to know any other reasons for using Objects.requireNonNull() in the beginning of the method.

推荐答案

因为这样做可以使事情明确。喜欢:

Because you can make things explicit by doing so. Like:

public class Foo {
  private final Bar bar;

  public Foo(Bar bar) {
    Objects.requireNonNull(bar, "bar must not be null");
    this.bar = bar;
  }

或更短:

  this.bar = Objects.requireNonNull(bar, "bar must not be null");

现在你知道


  • 使用 new()成功创建Foo对象

  • 然后 bar 字段保证非空。

  • when a Foo object was successfully created using new()
  • then its bar field is guaranteed be non-null.

比较一下:你今天创建一个Foo对象,明天你调用一个使用该字段并抛出的方法。最有可能的是,当它被传递给构造函数时,你明天不知道为什么那个引用是昨天

Compare that to: you create a Foo object today, and tomorrow you invoke a method that uses that field and throws. Most likely, you will not know tomorrow why that reference was null yesterday when it got passed to the constructor!

换句话说:明确地使用此方法检查传入引用,您可以控制引发异常的时间点。大多数时候,你想尽快失败

In other words: by explicitly using this method to check incoming references you can control the point in time when the exception will be thrown. And most of the time, you want to fail as fast as possible!

主要优点是:


  • 如上所述,控制行为

  • 更容易调试 - 因为你在对象的上下文中呕吐创建。在某个时间点你的日志/痕迹肯定会告诉你出了什么问题!

  • 并且如上所示:这个想法的真正力量与最终字段。因为现在类中的任何其他代码可以安全地假设 bar 不为空 - 因此您不需要任何 if(bar == null)在其他地方检查!

  • as said, controlled behavior
  • easier debugging - because you throw up in the context of the object creation. At a point in time where you have a certain chance that your logs/traces tell you what went wrong!
  • and as shown above: the true power of this idea unfolds in conjunction with final fields. Because now any other code in your class can safely assume that bar isn't null - and thus you do not need any if (bar == null) checks in other places!

这篇关于为什么要使用Objects.requireNonNull()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆