什么是番石榴的选修课的重点 [英] What's the point of Guava's Optional class
问题描述
我最近阅读了这篇文章并且看到了使用这个类的人,但是在几乎所有情况下,使用 null
也可以工作 - 如果不是更直观的话。有人可以提供一个具体的例子,其中可选
会实现 null
不能或者更简洁的方式吗?我唯一能想到的就是将它与 Maps
一起使用,它不接受 null
键,但即使这样可以用空值的一侧映射来完成。任何人都可以提供一个更令人信服的论点吗?谢谢。
Guava团队成员在这里。
可能是 null
的一个最大的缺点是,在任何给定的上下文中它的含义并不明显:它没有说明性的名称。这并不总是显而易见的, null
意味着这个参数没有值 - 作为返回值,有时它意味着错误,甚至成功(! !),或者简单地说正确答案是无关紧要的。 可选
通常是您在制作变量为可为空时的实际意思,但并非总是如此。如果不是,我们建议您编写自己的类,类似于可选
但使用不同的命名方案,以明确您的实际意思。
但我认为可选
的最大优点不在于可读性:优点是它的防白痴。如果你想让你的程序编译,它会迫使你主动思考这个缺失的情况,因为你必须主动打开 Optional
并解决这个问题。 Null使得简单地忘记事情变得非常容易,尽管FindBugs有所帮助,但我认为它几乎没有解决这个问题。当您返回可能或不可能存在的值时,这尤其重要。你(和其他人)更可能忘记 other.method(a,b)
可能会返回 null
值比你可能会忘记当你实现时,
。返回 a
可能是 null
other.method 可选
使得调用者不可能忘记这种情况,因为他们必须自己拆开对象。
出于这些原因,我们建议您使用可选
作为您的方法的返回类型,但不一定在您的方法参数中。
(顺便说一下,此处的讨论完全是这样。)
I've recently read about this and seen people using this class, but in pretty much all cases, using null
would've worked as well - if not more intuitively. Can someone provide a concrete example where Optional
would achieve something that null
couldn't or in a much cleaner way? The only thing I can think of is to use it with Maps
that don't accept null
keys, but even that could be done with a side "mapping" of null's value. Can anyone provide me with a more convincing argument? Thank you.
Guava team member here.
Probably the single biggest disadvantage of null
is that it's not obvious what it should mean in any given context: it doesn't have an illustrative name. It's not always obvious that null
means "no value for this parameter" -- heck, as a return value, sometimes it means "error", or even "success" (!!), or simply "the correct answer is nothing". Optional
is frequently the concept you actually mean when you make a variable nullable, but not always. When it isn't, we recommend that you write your own class, similar to Optional
but with a different naming scheme, to make clear what you actually mean.
But I would say the biggest advantage of Optional
isn't in readability: the advantage is its idiot-proof-ness. It forces you to actively think about the absent case if you want your program to compile at all, since you have to actively unwrap the Optional
and address that case. Null makes it disturbingly easy to simply forget things, and though FindBugs helps, I don't think it addresses the issue nearly as well. This is especially relevant when you're returning values that may or may not be "present." You (and others) are far more likely to forget that other.method(a, b)
could return a null
value than you're likely to forget that a
could be null
when you're implementing other.method
. Returning Optional
makes it impossible for callers to forget that case, since they have to unwrap the object themselves.
For these reasons, we recommend that you use Optional
as a return type for your methods, but not necessarily in your method arguments.
(This is totally cribbed, by the way, from the discussion here.)
这篇关于什么是番石榴的选修课的重点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!