用于可选 [英] Uses for Optional

查看:255
本文介绍了用于可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在使用 Java 8 6个月以上,我对新的API更改感到非常满意。我仍然不信任的一个领域是何时使用可选。我似乎在想要使用它之间的任何地方可能是 null ,而且无处可寻。

Having been using Java 8 now for 6+ months or so, I'm pretty happy with the new API changes. One area I'm still not confident in is when to use Optional. I seem to swing between wanting to use it everywhere something may be null, and nowhere at all.

似乎当我可以使用它时,会有很多情况,我永远不会确定它是否增加了益处(IE可读性/空值安全),或者只是造成额外的开销。

There seem to be a lot of situations when I could use it, and I'm never sure if it adds benefit (IE readability / null safety) or just causes additional overhead.

所以,我有几个例子,我对社区对可选是否添加的想法感兴趣效益。

So, I have a few examples, and I'd be interested in the community's thoughts on whether Optional adds benefit.

1 - 作为方法返回类型的方法可以返回 null

1 - As a public method return type when the method could return null:

public Optional<Foo> findFoo(String id);

2 - 当参数可能为 null

2 - As a method parameter when the param may be null:

public Foo doSomething(String id, Optional<Bar> barOptional);

3 - 作为豆的可选成员:

3 - As an optional member of a bean:

public class Book {

  private List<Pages> pages;
  private Optional<Index> index;

}

4 - 在集合

4 - In Collections:

一般来说,我不认为:

List<Optional<Foo>>

添加任何东西 - 特别是因为可以使用 filter()删除 null 值等,但是在集合中可选有什么好用吗?

adds anything - especially since one can use filter() to remove null values etc, but are there any good uses for Optional in collections?

我错过了任何情况?

推荐答案

可选是为返回值的函数提供一种方法,以指示不存在返回值。请参阅此讨论。这允许呼叫者继续流畅的方法调用链。

The main point of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.

这最接近OP的问题中的用例#1 。尽管如此,缺少值比 null 更为精确,因为像 IntStream.findFirst 之类的东西永远不会返回null

This most closely matches use case #1 in the OP's question. Although, absence of a value is a more precise formulation than null since something like IntStream.findFirst could never return null.

对于使用情况#2 ,将可选参数传递给方法,可以使其工作,但这很笨拙。假设你有一个方法,它接受一个字符串,后跟一个可选的第二个字符串。接受可选作为第二个参数会导致如下代码:

For use case #2, passing an optional argument to a method, this could be made to work, but it's rather clumsy. Suppose you have a method that takes a string followed by an optional second string. Accepting an Optional as the second arg would result in code like this:

foo("bar", Optional.of("baz"));
foo("bar", Optional.empty());

甚至接受null更好:

Even accepting null is nicer:

foo("bar", "baz");
foo("bar", null);

可能最好的方法是使一个重载的方法接受单个字符串参数,并为第二:

Probably the best is to have an overloaded method that accepts a single string argument and provides a default for the second:

foo("bar", "baz");
foo("bar");

这有一些限制,但是比以上任何一个都好。

This does have limitations, but it's much nicer than either of the above.

使用案例#3 #4 ,在课程中设置可选字段或数据结构被认为是滥用API。首先,它违反了顶部的可选的主要设计目标。第二,它不添加任何值。

Use cases #3 and #4, having an Optional in a class field or in a data structure, is considered a misuse of the API. First, it goes against the main design goal of Optional as stated at the top. Second, it doesn't add any value.

有三种方法来处理中可用的:提供替代值,调用函数来提供替代值,或者抛出异常。如果您正在存储到一个字段中,则可以在初始化或分配时执行此操作。如果您正在将列表中的值添加到列表中,那么您可以选择不添加该值,从而将缺少的值展平。

There are three ways to deal with the absence of a value in an Optional: to provide a substitute value, to call a function to provide a substitute value, or to throw an exception. If you're storing into a field, you'd do this at initialization or assignment time. If you're adding values into a list, as the OP mentioned, you have the additional choice of simply not adding the value, thereby "flattening" out absent values.

我敢肯定有人可以想出一些他们真的想在一个字段或集合中存储一个可选的案例,但一般来说,最好避免做这个。

I'm sure somebody could come up with some contrived cases where they really want to store an Optional in a field or a collection, but in general, it is best to avoid doing this.

这篇关于用于可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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