在地图中使用 Optional

Use of Optional in a map

好的,在我开始解释我的问题之前,我想让你知道我知道 Optional 背后的设计理念,并且它不打算用于字段或集合,但我已经编写了一个目前在 Kotlin 中有很多并且真的不喜欢使用 null.

所以我有一个基于节点的编辑器,就像 Unreal Engine 中那样,每个节点都有 ConnectionBoxes,它们可以是空闲的,也可以被 Connection.

所以有不同的方式来表达这一点,其中一种是使用将每个 ConnectionBox 映射到 Connection 的地图,例如:

Map<ConnectionBox, Connection> connectionEndPoints;
如果 ConnectionBox 是免费的,

Connection 可以是 null。我不喜欢这样,因为其他开发人员不知道此地图的功能,并且它可能 return null 对于现有的 ConnectionBox.

所以我很想使用:

Map<ConnectionBox, Optional<Connection>> connectionEndPoints;

它更好地显示了意图,您甚至可以像这样阅读它:
"This ConnectionBox may have a Connection attached."

我的问题是:为什么我不应该这样做,即使它更清楚地显示了意图并阻止了 NPEs。每个 SO 线程和每个博客 post 都说这是糟糕的风格,甚至编译器都说我不应该在警告的情况下这样做。


根据要求,这里有一个 SO 线程,不鼓励将 Optional 用作字段或集合值:Uses for Optional

这是警告(事实证明这是来自 IntelliJ 的警告):
警告:可选用作字段 {fieldName} 的类型


好的,在建议 Connection 参考应位于 ConnectioBox 内之后,问题就转移了。

为什么是:

class ConnectionBox {
    Optional<Connection> connection;
    ...

不如

class ConnectionBox {
    Connection connection; //may be null
    ...

除非我发表评论,否则您看不到您可能 运行 变成 NPE,我不喜欢评论解释可以自我解释的代码。

编辑

看完 Stuart Marks(在 Oracle JDK 小组的核心库团队工作)的演讲后 "Optional – The Mother of All Bikesheds" from Devoxx 2016, you should jump to 54:04:

Why Not Use Optional in Fields?

  • More a style issue than a correctness issue
    • usually there's a better way to model absence of a value
    • use of Optional in fields often arises from slavish desire to eliminate nullable fields
    • remember, eliminating nulls isn't a goal of Optional
  • Using Optional in fields...
    • creates another object for every field
    • introduces a dependent load from memory on every field read
    • clutters up your code
    • to what benefit? ability to chain methods?

原版Post

根据 IntelliJ 的检查器(首选项 > 编辑器 > 检查 > 'Optional' 用作字段或参数类型):

Optional was designed to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result". Using a field with type java.util.Optional is also problematic if the class needs to be Serializable, which java.util.Optional is not.

这也适用于集合,以防您必须 serialize 它们。此外,看看这些链接:

  • Java 8 Optional: What's the Point?

    So to recap - in an attempt to get rid of NullPointerExceptions we have a new class that:

    • Throws NullPointerExceptions
    • Can itself be null, causing a NullPointerException
    • Increases heap size
    • Makes debugging more difficult
    • Makes serializing objects, say as an XML or JSON for an external client, much more difficult
  • Why java.util.Optional is broken

    The final irony is that by attempting to discourage nulls, the authors of this class have actually encouraged its use. I'm sure there are a few who will be tempted to simply return null from their functions in order to "avoid creating an unnecessary and expensive Optional reference", rather than using the correct types and combinators.

如果您关心可读性,也可以使用 @Nullable(在 Eclipse as well as in IntelliJ 中可用):

class ConnectionBox {
    @Nullable
    Connection connection;
    // ...
}

或者,您可以创建一个可选的 getter:

class ConnectionBox {
    Connection connection;
    // ...
    Optional<Connection> getConnection() {
        return Optional.ofNullable(connection);
    }
}