Use of Optional in a map

一笑奈何 提交于 2019-12-04 06:20:33
beatngu13

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:

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?

Original Post

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

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:

  • 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.

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);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!