3 ms·
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
by bdamm 5y ago
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?
- rovolo 5y agoThe 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.
- dtech 5y agoLuckily 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.