是否有使用Optional.of()的真正原因? [英] Is there a real reason to use Optional.of()?

查看:842
本文介绍了是否有使用Optional.of()的真正原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读此处为何 Optional.of()应该在 Optional.ofNullable()上使用,但答案根本不满足我,所以我问略有不同:

I've read here why Optional.of() should be used over Optional.ofNullable(), but the answer didn't satisfy me at all, so I ask slightly different:

如果您确定您的方法没有返回 null ,为什么要使用可选?据我所知,它或多或少的唯一目的是提醒方法的用户,他可能不得不处理 null -values。如果他不必处理 null -values,他为什么要打扰 Optional

If you are SURE that your method does not return null, why should you use Optional at all? As far as I know, the more or less only purpose of it is to remind the "user of a method", that he might have to deal with null-values. If he does not have to deal with null-values, why should he be bothered with an Optional?

我问,因为我最近使我的服务层返回Optionals而不是nulls(在某些情况下)。我使用了 Optional.of(),当它抛出NullPointer时非常困惑。

I ask, because I recently made my service-layer return Optionals instead of nulls (in certain situations). I used Optional.of() and was highly confused when it threw a NullPointer.

我的样本确实:

Optional valueFromDB = getUserById("12");
User user = valueFromDB.get(); 

.....

public Optional<User> getUserById(String id) {
  //...
  return Optional.of(userRepository.findOne(id)); // NullPointerException!
}

如果无法使用null,我不明白为什么要包装它在可选中。链接答案中的家伙说:好吧,如果NullPointer发生,它会马上发生!但我真的想要吗?如果 Optional 的唯一目的是提醒获得此类对象的程序员,请记住 null (他要解开它),我为什么要在包装时有 NullPointerException

If null is not possible, I don't see why one would wrap it in an Optional. The dude in the linked answer said "well, if a NullPointer happens, it happens right away!" But do I really want that? If the sole purpose of an Optional is, to remind the programmer who gets such an object, to keep null in mind (he HAS to unwrap it), why should I want to have NullPointerException at wrapping-time?

编辑我需要编辑问题,因为它已被标记为重复,即使我已经从一开始就链接了所述问题。我也解释过,为什么答案不满足我,但现在我需要用解释来编辑我的文本。
但是这里有一些我想问的附录,因为我得到了5个答案,每个人都回答了不同的案例,但没有完全覆盖我在这里要求的内容:

I needed to edit the question, because it got marked as duplicate, even though I already linked said question from the start. I also did explain, why the answer did not satisfy me, but now I need to edit my text with an explanation. But here is some appendix to what I want to ask, since I got 5 answers and everyone answers a different case, but none fully covered what I try to ask here:

有没有理由,Optional.of(null)是不可能的,他们为null案例专门添加了Optional.ofNullable()?

使用流不应该是我对实现的想法的问题。
我从你的答案中得到了很多见解,谢谢你。但到目前为止,真正的问题还没有得到解答,据我所知/读/理解。
也许我应该问:如果我们删除 Optional.of()方法并且只允许 Optional.ofNullable()<怎么办? / code>在Java 9中,除了向后兼容性会有任何问题吗?

Using streams should not be the problem with my idea of the implementation. I got a lot of insight from your answers, thanks for that. But the real question has not been answered until now, as far as I can tell/read/understand. Maybe I should have asked: "What if we remove the Optional.of() method and only allow Optional.ofNullable() in Java 9, would there be any problem except backwards-compatibility?"

推荐答案

你正在混淆API设计原理以及特定实现代码中的知识。一个方法声明返回 Optional 是完全可能的,因为该值可能不存在,而在方法中的某个代码位置,它已知肯定存在。即。

You are mixing up the API design rationale with knowledge within a particular implementation code. It’s perfectly possible that a method declares to return an Optional, because the value might be absent, while at a certain code location within the method, it is known to be definitely present. I.e.

String content;
public Optional<String> firstMatch(String pattern) {
    Matcher m = Pattern.compile(pattern).matcher(content);
    return m.find()? Optional.of(m.group()): Optional.empty();
}

此方法的返回类型表示 String 可能不存在,而在创建可选实例的代码位置,可以知道该值是存在还是不存在。这不是要在这里检测 null 值。

This method’s return type denotes a String that might be absent, while at the code locations creating an Optional instance, it is known whether the value is present or absent. It’s not about detecting a null value here.

同样,在Stream API方法中 findFirst() findAny(),将在某一时刻知道是否存在匹配元素,同时支持其存在的转换如果匹配 null 元素,则显式不支持并且应该引发 NullPointerException 按规格。因此, Optional.of 将用于返回匹配元素,当使用 Stream.of((对象)时,您可以在堆栈跟踪中轻松识别该匹配元素)null).findAny();

Likewise, within the Stream API methods findFirst() and findAny(), it will be known at one point, whether there is a matching element, whereas supporting the conversion of its presence to absence in case of a matching null element is explicitly unsupported and supposed to raise a NullPointerException, per specification. Therefore, Optional.of will be used to return the matching element, which you can easily recognize in the stack trace when using Stream.of((Object)null) .findAny();

这篇关于是否有使用Optional.of()的真正原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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