|
>Yes, you can write get() and risk an exception. So don't do that. Yes, you can dereference a null pointer and risk an exception. So don't do that. See where this is going? The problem with Java's optional is that it is by all appearances (in name and high-level description), a general purpose optional, albeit with a ton of gotchas that will result in people saying "Just don't do that." Java's optional is not a general purpose option type. In fact, its intended use-case is very specific, according to a rather obscure SO answer by Brian Goetz: http://stackoverflow.com/a/26328555/547365 This is, of course, just tribal knowledge, meaning people are going to be doing shit with optional that they shouldn't, and it's going to be messy. |
>Yes, you can dereference a null pointer and risk an exception. So don't do that.
Except these aren't at all the same. With a reference, you have no good way of telling whether your reference IS nullable. With Optional, it's ALWAYS optional.
Therefore it is trivial to a) train developer habits to always check before fetch, and b) enforce an isPresent check with static checks.
Sure pattern decomposition is nicer, but that doesn't mean that Java's implementation "defeats the purpose entirely" like the author suggests. I'd love everything to be checked statically, but if that can't be done, I still like strong conventions which make the code clearer and safer.