4 ms·
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
by mleo 5y ago
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.
- dtech 5y agoI 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. [1] https://kotlinlang.org/docs/null-safety.html https://kotlinlang.org/docs/null-safety.html
- bdamm 5y agoThis 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.