4 ms·
I've only used the Guava version of Optional, which appears to have a slightly different API than Java 8's. (You can tell there's a Java 8 committee, that's fo
by jrockway 11y ago
I've only used the Guava version of Optional, which appears to have a slightly different API than Java 8's. (You can tell there's a Java 8 committee, that's for sure.)
The biggest problem I found in applying Optional is that Optional is very much a Haskell-y concept to me, and Java programmers and Haskell programmers don't really overlap much. Therefore, to me, Optional is just a functor like a list or a set. So doing Optional.asSet() and iterating over the result is, to me, the correct way way of handling an optional value. If there's something in there, the loop runs once. If there's not anything in there, the loop runs zero times. This is exactly like "fmap" in Haskell:
Prelude Data.Functor> fmap (+1) $ Just 42
Just 43
Prelude Data.Functor> fmap (+1) $ Nothing
Nothing
(Except that Haskell automatically preserves the type safety, whereas you have to re-wrap the value if you're using Java. Functional programming in Java never works, and this where the Optional idea starts to go wrong.)
But I got "I don't really understand this" in code reviews every time I did that; the Java way is to check if it's set, then do a type-unsafe unboxing. Thus, like the article said, completely defeating the purpose of the Optional type.
That said, it's pretty rare to need exactly 0 or 1 of something. If you're doing a database query, you can probably make the API return a set of rows. Then it's natural to loop over the results and nobody raises their eyebrows.
- tel 11y ago> That said, it's pretty rare to need exactly 0 or 1 of something. That's interesting and sort of hard to agree with. I think uniqueness is very often desirable and very often paired with a lack of certainty about existence. "Does a user with this identity exist?" certain is handled properly as a 0-or-1 question, e.g..
- jrockway 11y agoIs your method "getUserIfItExists(username)" or "doesUserExist(username)"?
- BorgHunter 11y agoIt's pretty common to need to do something to your user object if it does exist. As a toy example, it's far better to have something like (using Scala syntax here): def getUserGreeting(userDao: UserDAO)(username: String): String = userDao.getOptionalUser(username) match { case Some(user) => "Hello, " + user.getFullName case None => "Not logged in" } than: def getUserGreeting(userDao: UserDAO)(username: String): String = if(userDao.doesUserExist(username)) match { "Hello, " + userDao.get(username).getFullName } else { "Not logged in" } For one thing, the first function probably only makes one database call, while the second (absent caching) makes two. Secondly, the second carries with it the (unlikely) possibility that the user is deleted between your DAO calls. Thirdly, I would argue that the first function is easier to read.
- virtualwhys 11y ago2nd version wouldn't compile (need to remove "match"). probably more idiomatic for the 1st version would be: userDao.getOptionalUser(username).map(u=> s"Hello, ${u.getFullName}" ).getOrElse("Not logged in") i.e. string interpolate and map instead of match over Option.
- tel 11y agoCertainly "get". Sorry for the semantic confusion. Another word I use a lot is "lookup".
- peeters 11y agoIt always bothered me that Java8 and Guava optionals don't just implement Iterable. There must be a good reason for this, and I'm guessing they're worried about confusion when you have an `Iterable<List<T>>` but still, it'd be really nice to be able to just write for (T result : potentialResult ) { //... } I agree with you, that just seems so much more idiomatic than if (potentialResult.isPresent()) { T result = potentialResult.get(); } But maybe it comes from my mental model of Optional being a 0- or 1-length collection. It's at least definitely treated as a functor in that for pure functional operations, you have .map (or .transform for Guava).
- plonh 11y agoThe Guava authors believed Iterable would be confusing without calling .asSet() first.
- Sharlin 11y ago> Except that Haskell automatically preserves the type safety, whereas you have to re-wrap the value if you're using Java. Optional has map() in Java. Optional<Integer> result = Optional.empty().map(i -> i * i); assert(!result.isPresent()); Optional<Integer> result = Optional.of(9).map(i -> i * i); assert(result.get() == 81);