Re:Java 17 / JDK 17: General Availability
by throwaway4good on Tuesday September 14, 2021 @11:04AM
(#28525946)
You get null for free.
[ Parent
| on HN ]
Re:Java 17 / JDK 17: General Availability
by mleo on Tuesday September 14, 2021 @11:29AM
(#28526315)
Can’t tell if this meant to be a statement of fact, opinion or sarcasm. Over the course of 20 years have I have probably spent days of time tracking down NPEs in code being developed and after the fact in production releases. The amount of extra code and time spent to determine if variable is null certainly isn’t free.
Optional at least states the variable may not be referencing anything and provides helpful methods to chain mapping and conditionals to more easily deal with null values.
Re:Java 17 / JDK 17: General Availability
by dtech on Tuesday September 14, 2021 @11:46AM
(#28526537)
I really like the Kotlin approach, where they just embraced null being a fact of life on the JVM/JS and instead integrated nullability into the type-system [1]. C# and Typescript do something similar.
So then you get the best of both world, the safety of Optional without the boxing overhead.
Re:Java 17 / JDK 17: General Availability
by bdamm on Tuesday September 14, 2021 @12:59PM
(#28527584)
This really sounds like the way to go, although of course it is too late for Java. Optional feels awkward, and there's no more safety than we already have since the JVM null-checks anyway.
if( arg.isPresent() ) ...
vs if( arg != null ) ...
How is this better?
Re:Java 17 / JDK 17: General Availability
by rovolo on Tuesday September 14, 2021 @02:24PM
(#28528683)
The main advantage is that Optional is inconvenient and forces you to consider the null case. It's easy to forget that values can be null and assume they're not, e.g. auto-unboxing
Long getSomeValue();
int max = Math.max(0, obj.getSomeValue());
The Optional value forces you to type some text basically acknowledging that the value can be null. Optional<Long> getSomeValue();
... obj.getSomeValue().get());
I'm not saying Optional is a great solution. It's essentially a notification that a value is nullable.
Re:Java 17 / JDK 17: General Availability
by dtech on Wednesday September 15, 2021 @09:29AM
(#28538803)
Luckily it's not too late. A C#/Kotlin approach could be introduced and would not interfere with existing Optional.
The type system would need to be extended with a T? (nullable), T! (non-nullable), smart-casting on null-checks, and with some annotations or a flag to determine if T should be treated as T? or T! and whether you can call methods on it.
> How is this better?
It's not if you use Optional.get, but if you use .map, .orElse and the like the compiler can prevent you from getting NPEs instead of them being runtime.