Is this a valid (intended) usage of Optional type in Java 8?
String process(String s) {
return Optional.ofNullable(s).orElseGet(this::getDefault);
}
Is this a valid (intended) usage of Optional type in Java 8?
String process(String s) {
return Optional.ofNullable(s).orElseGet(this::getDefault);
}
Since this is more or less an opinion-based question, I'll throw mine in. If you're trying to say
then just say that. Making things "functional" doesn't automatically make things clearer or better. By introducing a needless
Optional
, a couple lambdas, and someOptional
methods that I had to look up, you've made the code more convoluted and difficult to understand. I don't think the designers of Java "intended" for people to useOptional
to help make code more obscure.EDIT: After reading some responses, I think it's worth adding some comments. This is not a functional programming idiom I'm familiar with, which would make it harder to understand. The idioms I am familiar with mostly involve Java streams, or (in other languages) functional idioms applied to multiple values in arrays or lists or other collections of multiple values. In those cases, once you get past the unfamiliarity, the functional syntax can be seen as an improvement because it allows some details to be hidden (loop indexes, iterators, running pointers, accumulator variables). So overall, it can simplify things. This example, by itself, doesn't do any such simplification.
However, some of the
Optional
features are useful in stream contexts. Suppose we had aparseInt()
method that returns anOptional<Integer>
, which is empty if the input string is invalid. (Java 8 really should have provided this.) This would make it easy to take an array of strings and produce an array of integers in which the strings that don't parse are simply eliminated from the result--useparseInt
in a streammap()
, and use a stream filter to filter out the emptyOptional
s. (I've seen multiple StackOverflow questions asking how to do this.) If you want to keep only the positive values, you could use anOptional.filter()
to change the nonpositives toOptional.empty()
before using the stream filter (although in this case, you could add another stream filter afterwards, but in a more complex case theOptional
filter could be more useful). That's what I see as the main benefit ofOptional
from a functional standpoint. It allows you to work with a collection of values all at once, by giving you a way to represent "non-values" and write a function that will still work with them. So I guess the main use ofOptional
, besides a replacement fornull
, would be to represent empty spaces in a sequence of values while you're applying functions to the entire sequence as a whole.Its a little contrived, but 'valid' (as in 'syntactically') , but as @yshavit pointed to, it was intended for use in library development.
Previous answer was due to FP code being difficult to read. Below is commented(a little verbose, b/c that is the javadoc comments) but still. Much easier to read IMHO. (2nd is no-comments, and at least alignment to help readability)
Or at least line it up so its more apparent what is going on and easier to read.
I'll take another swing at this.
Is this a valid usage? Yes, in the narrow sense that it compiles and produces the results that you're expecting.
Is this intended usage? No. Now, sometimes things find usefulness beyond what they were originally for, and if this works out, great. But for
Optional
, we have found that usually things don't work out very well.Brian Goetz and I discussed some of the issues with
Optional
in our JavaOne 2015 talk, API Design With Java 8 Lambdas and Streams:The primary use of
Optional
is as follows: (slide 36)The ability to chain methods from an
Optional
is undoubtedly very cool, and in some cases it reduces the clutter from conditional logic. But quite often this doesn't work out. A typical code smell is, instead of the code using method chaining to handle anOptional
returned from some method, it creates anOptional
from something that's nullable, in order to chain methods and avoid conditionals. Here's an example of that in action (also from our presentation, slide 42):The method that uses
Optional
is longer, and most people find it more obscure than the conventional code. Not only that, it creates extra garbage for no good reason.Bottom line: just because you can do something doesn't mean that you should do it.
Asking whether it's "valid" is rather opinion-based, but as to whether it's the intended use case: no, it's not.
Brian Goetz, Oracle's language architect for Java, has stated that the use case for Optional is for when you need a "no value" marker, and when using
null
for this is likely to cause errors. Specifically, if a reasonable user of your method is not likely to consider the possibility that its result isnull
, then you should use Optional. It was explicitly not intended to be a general "Maybe"-type object, as you're using it here.In your case, the method that returns the Optional is private. That means it can only be used by the implementers of the class, and you can assume that they have good knowledge of the class' methods — including which of them may return
null
. Since there's no reasonable risk of confusion, Brian Goetz would (probably) say that he would not consider this a valid use case.