This answer answers the question in the headline: "Should I not be optionally Serializable?" The short answer is that the Java Lambda expert group (JSR-335) reviewed and rejected it . This note, this one and this one, indicates that the main design goal for Optional should be used as the return value of functions when the return value may be absent. The goal is for the caller to immediately check Optional and retrieve the actual value, if present. If there is no value, the caller can replace the default value, throw an exception, or apply another policy. This is usually done by chaining fluent method calls from the end of the stream pipeline (or other methods) that return Optional values.
It was never intended to be used by Optional other ways, for example, for optional method arguments or for being stored as a field in an object . And, by extension, the creation of Optional serializable would allow it to be permanently stored or transmitted over the network, both of which encourage use far beyond their original design goals.
There are usually better ways to organize data than storing Optional in a field. If the recipient (for example, the getValue method in the question) returns the actual Optional from the field, it forces each caller to implement some policy for working with an empty value. This is likely to lead to inconsistent behavior among subscribers. It is often better that the sets of codes used in the field apply a certain policy at the time of its installation.
Sometimes people want to put Optional in collections, such as List<Optional<X>> or Map<Key,Optional<Value>> . This is also usually a bad idea. It is often better to replace these Optional usages with Null-Object (not relevant null references) or simply omit these entries from the collection completely.
Stuart Marks Jul 03 '14 at 23:19 2014-07-03 23:19
source share