在地图中使用Optional [英] Use of Optional in a map

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

问题描述

好,在我开始解释我的问题之前,我想让你知道我了解Optional背后的设计思想,并且不打算将其用于领域或馆藏中,但是我目前在Kotlin中进行了大量编程真的不喜欢使用null.

Ok before I start explaining my question I want you to know that I know about the design idea behind Optional and that it isn't intended to be used in fields or collections, but I have programmed a lot in Kotlin currently and really dislike using null.

因此,我在虚幻引擎中有一个基于节点的编辑器,每个节点都有ConnectionBox es,它们可以是免费的,也可以由Connection占据.

So I have a Node based editor like in the Unreal Engine and each node has ConnectionBoxes, which can be either free or are occupied by a Connection.

因此有多种表达方式,其中一种是使用将每个ConnectionBox映射到Connection的映射,例如:

So there are different ways to express this one of which is using a map that maps each ConnectionBox to a Connection like:

Map<ConnectionBox, Connection> connectionEndPoints;

如果ConnectionBox是空闲的,则

Connection可能是null.我不喜欢这样,因为其他开发人员不了解此Map的功能,并且它可能为现有的ConnectionBox返回null.

and Connection could be null if the ConnectionBox is free. I don't like this, since an other developer doesn't know about the function of this Map and that it may return null for an existing ConnectionBox.

所以我很想使用:

Map<ConnectionBox, Optional<Connection>> connectionEndPoints;

可以更好地显示目标,您甚至可以像下面这样阅读:
ConnectionBox可能附加了Connection."

which displays the intend much better and you can even read it like:
"This ConnectionBox may have a Connection attached."

我的问题是:为什么我不应该这样做,即使它可以更清楚地表明意图并阻止NPE.每个SO线程和每个博客帖子都说这是不好的风格,甚至编译器都说我不应该发出警告.

My question is: Why should I not do this, even though it shows the intend much more clearly and prevents NPEs. Every SO-thread and every blog post says this is bad style and even the compiler say that I shouldn't do it with a warning.

应要求提供的SO线程不鼓励将Optional用作字段或Collection值:

On request here is a SO-thread that discourages use of Optional as a field or Collection value: Uses for Optional

这是警告(事实证明是IntelliJ发出的警告):
警告:用作字段{fieldName}

And here is the warning (as it turns out it is a warning from IntelliJ):
Warning: Optional used as type for field {fieldName}

在建议Connection引用应该位于问题刚刚出现的ConnectioBox之内后,确定.

Ok after recommending that the Connection reference should lie within the ConnectioBox the question just shifts.

为什么是

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

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

除非我发表评论,否则您看不到您可能会遇到NPE,而且我不喜欢评论解释可以自我解释的代码的情况.

Unless I make a comment you can't see that you may run into a NPE and I dislike comments explaining code that could explain itself.

推荐答案

编辑

看完Stuart Marks(在Oracle JDK组的核心库团队工作的人)后,谈话,您应该跳转到

Edit

After watching Stuart Marks' (who works for the core libraries team in the JDK group at Oracle) talk "Optional – The Mother of All Bikesheds" from Devoxx 2016, you should jump to 54:04:

为什么在字段中不使用可选内容?

  • 更多的是样式问题,而不是正确性问题
    • 通常有一种更好的方法来模拟缺少值的情况
    • 在字段中使用Optional通常是由于人们渴望消除可空字段
    • 记住,消除空值不是Optional的目标

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
  • 为每个字段创建另一个对象
  • 在每次读取的字段中引入来自内存的依存负载
  • 整理您的代码
  • 有什么好处?链接方法的能力?
  • 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?

原始帖子

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

Original Post

According to IntelliJ's inspector (Preferences > Editor > Inspections > 'Optional' used as field or parameter type):

Optional旨在为库方法返回类型提供一种有限的机制,该机制需要一种明确的方式来表示无结果".如果类需要为Serializable,而类型为java.util.Optional,则使用类型为java.util.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.

这也适用于您必须序列化的集合.此外,请查看以下链接:

This also applies to collections in case you have to serialize them. Furthermore, have a look at these links:

所以回顾一下-为了摆脱NullPointerExceptions,我们有一个新类:

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

  • 引发NullPointerExceptions
  • 本身是否可以为null,从而导致NullPointerException
  • 增加堆大小
  • 使调试更加困难
  • 使序列化对象变得困难,例如,将对象序列化为XML或JSON作为外部客户端
  • 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

  • 为什么java.util.Optional损坏了

    最后具有讽刺意味的是,通过尝试阻止null,此类的作者实际上鼓励了它的使用.我敢肯定有些人会被诱惑从他们的函数中简单地返回null,以便避免创建不必要的和昂贵的Optional引用",而不是使用正确的类型和组合器.

    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(在

    If you care about readability, you could also use @Nullable (available in Eclipse as well as in IntelliJ):

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

    或者,您可以创建一个可选的吸气剂:

    Alternatively, you can create an optional getter:

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

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

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