The author is missing the point. The fact that Optional can result in a nullpointer doesn't mean you should use in the same manner as null-checks. You shouldn't replace: if(x == null) { y = x.doSomething(); } with if(optionalX.isPresent()) { y = x.doSomething(); } You should replace it with: y = Optional.ofNullable(x) .map(ClassX::doSomething) .orElse(null);
Java 8’s new Optional type doesn't solve anything
71–80 of 197 posts
Re: Java 8’s new Optional type doesn't solve anything
#72Earlier quoted context omitted.
Yes. In this case the No-result means that the database query was successful, but no record was found. A connection error etc. should almost certainly still be thrown as an exception in Java. Without exceptions you would have to return a value that could discriminate between all 3 possible outcomes: nothing, error, result. In Rust this is the `Result ` struct.
It that case, wouldn't it be better to return something other that `null` for no-result (an empty iterator? an empty list?)? That might be where Optional comes in, but I'm still not sure why a new language feature is needed for that.
Re: Java 8’s new Optional type doesn't solve anything
#73Earlier quoted context omitted.
The author is missing the point. Is he? The point is that in Java you are still able to treat x unsafely, while languages with stronger typing do not. E.g. in Haskell, if a function returns a Maybe a , it will always be a Just a or Nothing value. Moreover, such languages allow you to make non-exhaustive matching against all constructors a compiler error. tl;dr: Haskell, Rust, et al. put the burden on the compiler. Ja…
>tl;dr: Haskell, Rust, et al. put the burden on the compiler. Java puts the burden to ensure safety on the programmer. (As can be witnessed in your snippet.) Actually, (much to my disappointment as I'm just learning rust) you can just take an Option or Result and .unwrap() and the compiler won't complain at you for not checking it. For such a "safe" strongly-typed language, I'm surprised that so much new rust code do…
That said, I think you're too dismissive of "can never fail" assumptions. There's tons of places where something is optional in general, but based on various invariants you know it won't be. For instance, if you successfully acquire the first element in an array, you know you can get the last.
If you legitimately believe that Option is always Some, I don't understand what you think you would otherwise put there? Gonna have your function return an Err if an internal invariant is broken? Gonna have callers actually check for that?
Re: Java 8’s new Optional type doesn't solve anything
#74Using get() is just bad style and so is returning null where you could return Collections.emptyList(). Previous discussion on reddit: https://www.reddit.com/r/programming/comments/3pl7o0/java_8s... tl;dr: use map, orElseGet, orElse
Why it's bad? If I'm sure that this optional contains value, I don't see why it's bad. May be I checked this value presence few lines above.
Checking presence of value of an optional is an anti-pattern, the same as doing != null checks.
You should treat Optional the same as a List type with size 1. You never check if a list is size 1 before doing map or filter.
Re: Java 8’s new Optional type doesn't solve anything
#75Earlier quoted context omitted.
> A programmer looking at the code for the first time will know, just by looking at the return type, "Hey, this method may not return a record! I'll have to handle that scenario." Well, that's basically the same thing with any nullable return then. Wether I return T or Optional , there might be no record. Even worse, when I return T, you only have 2 cases : I return something, or I return null. With optional, you hav…
I am not sure I understand. I guess you are either saying (A) to treat every return type as possibly null or (B) to use your judgment when doing null checks of return types. In case of (A): Do you want to write null-checks for methods like String.toUpperCase() or for user.getLastName() ? That would lead to a lot of bloated, dead code. Also do you want to write error handling for all these cases you know can never hap…
Re: Java 8’s new Optional type doesn't solve anything
#76Earlier quoted context omitted.
Exactly, it forces the programmer to think about whether something can be null or not and actually had a behavioural change in my java coding.
> Exactly, it forces the programmer to think It's a curious feature, the way you've described it. I have virtually no experience with Java so I'm looking at this from a totally foreign perspective. The authors considers it an ineffective feature because you still have to think about null checks, whereas you consider it an effective feature because it forces you to think about the problem instead of ignoring it.
Re: Java 8’s new Optional type doesn't solve anything
#77Adding my voice to the din of people noting how far afield of the point the author is: You should almost never call .get(), except in cases where the code path does not allow an empty optional. Even so, calling .get() on an empty optional is better than handing nulls around. A null may -- by chance, really -- make it several lines down the code, so that the stack trace points you much later in the code than where the…
E.g., imagine you got a NPE from this:
String summary = getUserSummary( user.getId() );
...you'd think "user" must be null, right? But it's quite possible that user.id is a Long, the current value is null, and getUserSummary() requires a long primitive argument.This compiles just fine, and at runtime the Long object will be auto-unboxed to a primitive long... unless it's null.
Surprise!
But things like Optional do help; doing a code review for the things that may be null will fix these kinds of mismatches (and you'll avoid relying on auto-unboxing). The above code is broken -- either user.getId() can never be null (in which case it should be a primitive already) or it might sometime be null, in which case this code must not allow auto-unboxing.
Re: Java 8’s new Optional type doesn't solve anything
#78Earlier quoted context omitted.
Why it's bad? If I'm sure that this optional contains value, I don't see why it's bad. May be I checked this value presence few lines above.
If you are certain optional has a value, don't use optional. Checking presence of value of an optional is an anti-pattern, the same as doing != null checks. You should treat Optional the same as a List type with size 1. You never check if a list is size 1 before doing map or filter.
getCharsetOpt("UTF-8")
There is no way this code will return None in this particular case. So any additional checks are unnecessary and make code less readable.Re: Java 8’s new Optional type doesn't solve anything
#79We tried to use Optional instead of returning null. Accidentally returning null from methods returning Optional is something that actually happens, especially when migrating existing code. Of course you can solve that with @Nonnull annotations, but then why use Optional in the first place? The other problem is that the Optional interface is clunky. There is ifPresent(), but no ifAbsent(). The stream syntax is incompa…
That's what map/flatMap is for, ifPresent is really only useful for side-effects.
Re: Java 8’s new Optional type doesn't solve anything
#80Earlier quoted context omitted.
>tl;dr: Haskell, Rust, et al. put the burden on the compiler. Java puts the burden to ensure safety on the programmer. (As can be witnessed in your snippet.) Actually, (much to my disappointment as I'm just learning rust) you can just take an Option or Result and .unwrap() and the compiler won't complain at you for not checking it. For such a "safe" strongly-typed language, I'm surprised that so much new rust code do…
Just to clarify since `unsafe` is a special term in Rust: `unwrap` still checks for None and panics, it doesn't blindly assume it's valid. That said, I think you're too dismissive of "can never fail" assumptions. There's tons of places where something is optional in general, but based on various invariants you know it won't be. For instance, if you successfully acquire the first element in an array, you know you can…
Absolutely you should return an error. Whether the caller wants to panic or handle it or print unicorns should be left up to the caller, not your function. Functions should not be expected to tear down the thread in case of an error. Nothing that panics should belong anywhere in exported code