3 ms·
I think the obvious right answer is to not have null in the language, and use an option type instead. There might be a better solution, but I haven't come acros
by wtetzner 11y ago
I think the obvious right answer is to not have null in the language, and use an option type instead. There might be a better solution, but I haven't come across one yet.
Of course, it's too late for Java now. They have an Optional<T> type, but removing null from the language would break backwards compatibility. Of course, that means that a method that returns Optional<T> might return an Optional<T>, or null, so now you have 2 things to check instead of one :).
- DannoHung 11y agoHeh, maybe Java 9(10? I have no idea what number they are currently working on) could forbid types that return Optional<T> from being null.
- labianchin 11y agoJava 10 is supposed to introduce value types, that will change the way we use nulls, check here: http://blog.joda.org/2014/11/better-nulls-in-java-10.html http://blog.joda.org/2014/11/better-nulls-in-java-10.html
- masklinn 11y ago> There might be a better solution, but I haven't come across one yet. An Option type (and/or an Either type as well) is a good base, but if you can create a null object itself it's still better.
- wtetzner 11y agoCan you elaborate?
- shanemhansen 11y agoIt's not a full solution, but java has support for nonnullable annotations so under certain situations the compiler will guarantee that you don't need to check for null. Backwards compatibility's a PITA. http://types.cs.washington.edu/checker-framework/current/checker-framework-manual.html#nullness-checker http://types.cs.washington.edu/checker-framework/current/che...
- wtetzner 11y agoYeah, I've looked into that, but you have to use their special compiler to build. I can't find a way to use it in a Maven build that doesn't require the user to install the checker framework locally.
- Dewie3 11y ago> Of course, that means that a method that returns Optional<T> might return an Optional<T>, or null, so now you have 2 things to check instead of one :). NO. Just don't check for null and let it fail -- that will uncover a bug, namely using `null` when they should have used "None" or whatever it's called in Java. Do people defensively check for null for every object access in java? I hope not, because that would be really tedious and obfuscate all logic bugs relating to inappropriate uses of null.
- wtetzner 11y agoThe problem with not checking for null is that it won't fail soon enough. null will get passed along until someone tries to call a method on it, at which point you'll get a NullPointerException. But at that point you don't know where the null came from. It's better to fail early. Lombok can help with this, with its @NonNull annotation, but that only helps so much.
- Dewie3 11y agoDo you assert that all object variables that cross an interface boundary are not null (`assert var != null`)?