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

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

问题描述

我已阅读此处为什么可选.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,那么您为什么要使用Optional?据我所知,它或多或少的唯一目的是提醒方法的用户",他可能不得不处理 null 值.如果他不必处理 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?

我问,因为我最近让我的服务层返回可选值而不是空值(在某些情况下).我使用了 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 是不可能的,我不明白为什么要把它包装在 Optional 中.链接答案中的家伙说:好吧,如果 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()?

使用流应该不是我的实现想法的问题.从你的回答中我得到了很多见解,谢谢.但据我所知/阅读/理解,直到现在真正的问题还没有得到回答.也许我应该问:如果我们在 Java 9 中删除 Optional.of() 方法并只允许 Optional.ofNullable() 会怎样,除了向后兼容?"

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,而在创建 Optional 实例的代码位置,知道该值是否存在.这里不是检测 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((Object)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天全站免登陆