用于可选 [英] Uses for Optional

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

问题描述

现在使用 Java 8 已有 6 个多月的时间,我对新的 API 更改感到非常满意.我仍然不确定的一个方面是何时使用 Optional.我似乎在想要在任何可能是 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.

似乎在很多情况下我都可以使用它,但我不确定它是否增加了好处(可读性/空值安全),或者只是增加了额外的开销.

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

所以,我举了几个例子,我对社区关于 Optional 是否有益的想法很感兴趣.

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

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 - 作为 bean 的可选成员:

3 - As an optional member of a bean:

public class Book {

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

}

4 - 在 Collections 中:

总的来说,我不认为:

List<Optional<Foo>>

添加任何东西 - 特别是因为可以使用 filter() 删除 null 值等,但是 Optional 在收藏?

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

有我遗漏的案例吗?

推荐答案

Optional 的主要设计目标是为函数返回值提供一种方法,以指示没有返回值.请参阅此讨论.这允许调用者继续一系列流畅的方法调用.

The main design goal 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,将可选参数传递给方法,这可以起作用,但它相当笨拙.假设您有一个方法,它接受一个字符串,后跟一个可选的第二个字符串.接受 Optional 作为第二个参数会导致这样的代码:

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,在类字段或数据结构中具有Optional,被视为滥用API.首先,它违背了顶部所述的 Optional 的主要设计目标.其次,它没有增加任何价值.

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.

处理Optional中没有值的三种方法:提供替代值,调用函数提供替代值,或抛出异常.如果要存储到字段中,则应在初始化或分配时执行此操作.如果您将值添加到列表中,正如 OP 所提到的,您可以选择不添加值,从而扁平化"列表.排除缺失值.

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.

我敢肯定有人会想出一些人为的情况,他们真的想在字段或集合中存储 Optional,但一般来说,最好避免这样做.

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天全站免登陆