可选的nullable()和`可选的opational.of()有什么区别

发布于 2025-01-20 18:14:44 字数 771 浏览 0 评论 0 原文

首先我知道这两种方法的区别。

  • Optional.of :用于保证不存在null,如果输入null,则为nullPointException

  • Optional.ofNullable :可能为 null,也可能不为 null。用于灵活应对。

那么,如果我添加 orElseThrow(() -> new NullPointerException("null data")) 到此,它最终会是相同的吗?

我想抛出带有显式内容的错误。

所以我得到 Optional.ofNullable(data).orElseThrow(() -> new NullPointerException("null data")))

使用它作为这是无意义的行为吗?

Optional.of(data).orElseThrow(() -> new NullPointerException("null data")))

我认为这也是可能的,但我只是使用 ofNullable() 使代码看起来一致。

总而言之, 最后,如果添加 orElseThrow(nullPoint) ofofNullable 结果相同吗?

那么相反 of.orElseThrow 更好吗?

First of all, I know the difference between the two methods.

  • Optional.of : Used to ensure that there is no null, if null is entered, nullPointExcepction

  • Optional.ofNullable : may or may not be null. Used to respond flexibly.

So, if I add orElseThrow(() -> new NullPointerException("null data")) to this, will it end up being the same?

I want to throw an error with explicit content.

So I get Optional.ofNullable(data).orElseThrow(() -> new NullPointerException("null data")))

use it as Is this pointless behaviour?

Optional.of(data).orElseThrow(() -> new NullPointerException("null data")))

I think this is also possible, but I'm just using ofNullable() to make the code look consistent.

to sum it up,
In the end, if you add orElseThrow(nullPoint)
Are of or ofNullable the same result?

then rather
Is of.orElseThrow better?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伴梦长久 2025-01-27 18:14:45

总结一下,最后如果加上 orElseThrow(nullPoint) of 或 ofNullable 结果是一样的吗?

不。要看到这一点,只需查看类型即可。

公共静态;可选的 (T值);

public  T orElseThrow(Supplier 异常供应商)
                               throws X 扩展了 Throwable;

Optional.of 返回一个 Optional,其中 orElseThrow 将为您留下一个 T。所以 Optional.ofNullable(x).orElseThrow(...) 实际上只是一个非常迂回的方法,

if (x == null) {
  throw new NullPointerException(...);
}

您实际上并没有使用 Optional做任何事情>,只是制作一个并以一种非常冗长的方式丢弃它。因此,如果这是您的意图,只需执行显式 null 检查即可;根本不需要可选

这就提出了一个问题:为什么我们要使用 ofofNullable。随着Optional的引入,现在Java中有两种方法来表示“这个值可能不存在”的概念:nullOptional.empty() 。互联网上的人们会争论到底哪个更好,什么时候应该使用哪个(我对此有强烈的意见,我不会在这里分享,因为这不是你问的),但重点是有两种不同的方法可以做到这一点。

在本文的其余部分,我将借用 Kotlin 的一些符号并编写 T? 来表示“一个可能为 null”的 T代码>”。这不是有效的 Java 表示法,但它表达了要点。因此,如果我们想在 Java 中表示“A T 可能存在,也可能不存在”,我们可以使用 OptionalT?

如果我们想从 T? 转到 Optional,这就是 Optional.ofNullable 的用途。它说“如果该东西是null,则给我Optional.empty();否则给我Optional中的东西”。反之,我们可以使用 Optional.orElse(null),它表示“如果我有一个 T,请将其给我,否则显示给我 ”。所以现在我们有一种方法可以在两种方法之间进行转换。那么Optional.of有什么用呢?

您应该将 Optional.of 视为某种断言。如果 Java 具有像 Kotlin 一样可为 null 的类型,那么差异将类似于

public static <T> Optional<T> of(T value);
public static <T> Optional<T> ofNullable(T? value);

That is, ofNullable 期望其值可能为 nullof 已经假设事实并非如此。 Optional.of 应该被认为是一个断言,即您给它的值不为空。如果该断言失败,我们会立即抛出 NullPointerException,而不是让错误传播到程序的其他部分。如果您调用 Optional.of 并从抛出[1]NullPointerException 中恢复,那么您正在做一些非常错误的事情。该函数是我们首先处理非空数据的断言,如果该断言失败,那么您的程序应该立即失败,并具有良好的堆栈跟踪。

听起来,根据您的用例,您的值可能为 null。在这种情况下,Optional.ofNullable 就有意义了;它已准备好处理用例。如果您想引发自定义异常,则应事先进行 null 检查(因为是处理 null 的人,而不是可选 ),然后调用Optional.of。或者,当然,如果您打算使用 orElseThrow 来提取它,您可以只进行老式的 null 检查,根本不使用 Optional 。当然,一行中的管道 Optional.ofNullable(value).orElseThrow(...) 会产生代码味道。


[1] 请注意,我说的是“从中恢复”,而不是“捕获”。记录所有错误的优秀顶级 catch (Exception exc) 是完全可以接受的,并且在大型应用程序中通常是一个好主意。但是如果你正在执行 catch (NullPointerException exc) { return 0; } 或类似的东西,那么您需要重新考虑应该使用哪种 Optional 方法。

to sum it up, In the end, if you add orElseThrow(nullPoint) Are of or ofNullable the same result?

No. To see this, simply look at the types.

public static <T> Optional<T> of(T value);

public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
                               throws X extends Throwable;

Optional.of returns an Optional<T>, where orElseThrow is going to leave you with a T. So Optional.ofNullable(x).orElseThrow(...) is really just a very roundabout

if (x == null) {
  throw new NullPointerException(...);
}

You're not actually doing anything with the Optional, just making one and discarding it in a really verbose way. So if that's your intent, just do an explicit null check; there's no need at all for Optional.

Which raises the question of why we would use of or ofNullable. With the introduction of Optional, there are now two ways to represent the concept of "this value might not exist" in Java: null and Optional.empty(). People on the Internet will argue till the end of time about which is better and when you should use which one (I have strong opinions on this which I'll refrain from sharing here, since it's not what you asked), but the point is that there are two different ways to do it.

For the rest of this post, I'll borrow a bit of notation from Kotlin and write T? to mean "a T value which might be null". It's not valid Java notation, but it gets the point across. So if we want to represent "A T which may or may not exist" in Java, we can use either Optional<T> or T?.

If we want to go from T? to Optional<T>, that's what Optional.ofNullable is for. It says "If the thing is null, give me Optional.empty(); otherwise give me the thing in an Optional". To go the other way, we can use Optional.orElse(null), which says "If I have a T, give it to me, otherwise show me null". So now we have a way to convert between the two approaches. So what's Optional.of for?

You should view Optional.of as an assertion of sorts. If Java had nullable types like Kotlin, then the difference would be something like

public static <T> Optional<T> of(T value);
public static <T> Optional<T> ofNullable(T? value);

That is, ofNullable expects that its value might be null. of is already assuming that it's not. Optional.of should be thought of an assertion that the value you're giving it is not null. If that assertion fails, we throw NullPointerException immediately rather than letting errors propagate to other parts of the program. If you're calling Optional.of and recovering from the NullPointerException it throws[1], then you are doing something very wrong. That function is an assertion we were dealing with non-null data to begin with, and if that assertion fails then your program should fail immediately with a good stack trace.

It sounds like, based on your use case, you have a value that might be null. In that case, Optional.ofNullable makes sense; it's prepared to handle the use case. If you want to throw a custom exception, you should do a null check beforehand (since you're the one handling the null, not Optional) and then call Optional.of. Or, of course, you can just do an old-fashioned null check and not use Optional at all, if you're planning to extract it anyway with orElseThrow. Certainly, the pipeline Optional.ofNullable(value).orElseThrow(...) in one line would be a code smell.


[1] Note that I say "recovering from", not "catching". A nice top-level catch (Exception exc) which logs all errors is perfectly acceptable and generally a good idea in larger applications. But if you're doing catch (NullPointerException exc) { return 0; } or something like that then you need to reconsider which Optional method you should be using.

浪漫之都 2025-01-27 18:14:45

首先我知道这两种方法的区别。

Optional.of :用于确保不存在 null,如果 null
输入,nullPointException

Optional.ofNullable :可能是也可能不是null。用于回应
灵活运用。

有一个明显的误解。

Optional.of() 的目的不是“确保不存在 null”。它并不意味着用作传递给它的值是非空的断言。对于这样的验证,您可以使用 Objects.requireNonNull(),它要么抛出一个 NPE,要么返回一个 non-无效的值。

为了达成共识,您必须牢记的第一件重要事情是,JDK 中引入可选选项仅用于一个特定目的 - 充当返回类型。当可选用作参数类型或字段类型,或者可选对象存储在集合中时,任何其他情况都不被认为是一个好的做法。同样,创建一个可选只是为了在其上链接方法或隐藏空检查,被认为是反模式

以下是 JDK 开发者 @StuartMarks 的回答中的几句话

Optional的主要用途如下:

可选的目的是
为库方法返回类型提供有限机制,其中
显然需要表示“无结果”,并且使用 null
因为这极有可能导致错误。

典型的代码味道是,而不是使用方法链接的代码
处理从某个方法返回的Optional,它创建一个Optional
来自可为空的东西,为了链接方法避免
条件句

我还建议您看看这个问题的答案 “ShouldOptional.ofNullable() 用于空检查吗? “,同样由斯图尔特·马克斯创作。

话虽如此,组合 Optional.of().orElseThrow() 既错误又毫无意义:

  • 如果提供的数据为 null 方法 of() 将引发 NPE 并且 orElseThrow() 将不会被执行(即它的异常永远不会被触发)。
  • 您通过创建可选对象来滥用可选对象,不是为了返回由它包装的可为空变量,而是为了隐藏空检查(采取看看上面的引用)。这掩盖了代码的目的。如果给定值不能为 nullrequireNonNullElse() 来提供默认值,您可以使用 Objects.requireNonNull() 来引发异常价值。

出于同样的原因,您不应该首先使用 Optional.ofNullable().orElseThrow()

可选就像一个盒子

您可能会认为可选是它是包裹。当您需要发送某些内容时,您会前往邮局(即从该方法返回),需要发送的内容将被放入一个 >框。当某人(呼叫者)收到包裹时,它会立即被拆包。这就是名为Optional 的盒子的整个生命周期。

根据应用程序的逻辑,当需要从方法返回的对象不应为 null 时 - 使用 Optional.of()。它要么成功发送包裹,要么通过引发 NullPointerException 来强调存在问题。

如果给定对象本质上可以为空,即null不是异常情况,那么使用Optional.ofNullable(),它'将发射一个包含该物体的盒子或一个空盒子。

调用者即调用返回可选值的方法的方法)必须使用各种工具来打开盒子 可选提供诸如orElseThrow()orElseGet()ifPresent()等。

First of all, I know the difference between the two methods.

Optional.of : Used to ensure that there is no null, if null is
entered, nullPointExcepction

Optional.ofNullable : may or may not be null. Used to respond
flexibly.

There's a clear point of misunderstanding.

The purpose of Optional.of() is not "to ensure that there is no null". It is not meant to be used as an assertion that a value that was passed into it is non-null. For such a validation you can use Objects.requireNonNull(), it'll either throw an NPE, or will return you a non-null value.

In order to be on the same page, the first important thing you have to keep in mind is that optionals were introduced in the JDK for only one particular purpose - to serve as a return type. Any other cases when optional is utilized as a parameter-type, or a field-type, or when optional objects are being stored in a collection isn't considered to be a good practice. As well, as creating an optional just in order to chain methods on it or to hide a null-check is considered to be an antipattern.

Here is a couple of quotes from the answer by @StuartMarks, developer of the JDK:

The primary use of Optional is as follows:

Optional is intended to
provide a limited mechanism for library method return types where
there is a clear need to represent "no result," and where using null
for that is overwhelmingly likely to cause errors.

A typical code smell is, instead of the code using method chaining to
handle an Optional returned from some method, it creates an Optional
from something that's nullable, in order to chain methods and avoid
conditionals
.

I also suggest you to have a look at this answer to the question "Should Optional.ofNullable() be used for null check?", also by Stuart Marks.

With all that being said, combination Optional.of().orElseThrow() is both wrong and pointless:

  • If provided data is null method of() will raise an NPE and orElseThrow() will not be executed (i.e. its exception will get never be fired).
  • You're abusing the optional by creating an optional object not in order to return a nullable variable wrapped by it, but to hide the null-check (take a look at the quote above). That obscures the purpose of your code. You can use Objects.requireNonNull() instead to throw an exception if the given value must not be null or requireNonNullElse() to provide a default value.

For the same reason, you shouldn't use Optional.ofNullable().orElseThrow() at the first place.

Optional is like a Box

You might think of optional is if it is a parcel. When you need to send something, you go to the post office (i.e. returning from the method), where the thing that has to be sent is being placed into a box. When somebody (i.e. the caller) receives the parcel, it is being immediately unpacked. That is the whole lifecycle of the box called Optional.

When, according to the logic of your application, an object required to be returned from the method should not be null - use Optional.of(). It'll either send a parcel successfully or will emphasize that there's a problem by raising a NullPointerException.

If the given object is nullable by its nature, i.e. null isn't an abnormal case, then use Optional.ofNullable(), it'll fire either a box containing the object or an empty box.

And the caller (i.e. method that invokes the method returning an optional) is the one who has to unpack the box using a variety of tools that optional provides like orElseThrow(), orElseGet(), ifPresent(), etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文