Null Safety approach with forced "!"
Am I the only one who thinks that introducing protection against NPEx in the form of using "!" in the variable type is a very, very bad idea? In my experience, 95% of variables should be non-null. If Oracle decides to take this approach, we will have millions of "!" in each variable in the code, which is tragic for readability. In C#, you can set the per project flag to indicate whether the type without the "?" /"!" is nullable or not. I understand the drawbacks, but definitely forcing a "!" in 95% of variables is tragic.
78
Upvotes
View all comments
Show parent comment
5
u/rzwitserloot Feb 26 '26
Problem 2 of 2: Backwards compatibility
Let's look at existing interface
java.util.List. It has a method:It's spec (the javadoc) explains that this method is to throw a
NullPointerExceptionifais null. I guess if we want to be excruciatingly technically pedantic, that means the correct signature isT[]?(and note how that's different fromT?[]! There's both the notion 'a possibly null array of definitely not null strings' and 'a definitely not null array of possibly null strings') given that the API explicitly says thatnullis allowed and simply causes an NPE to be thrown. But that's.. silly, so let's update it:tada! Any code that this breaks, i.e. any code that intentionally calls
toArray(null)and/or returnsnulland expects some behaviour out of this.. no problem - that's code that failed to read the spec.Except, not so fast. It is possible that someone writes code that passes possibly-null arrays to
toArrayand deals with the NPE. After the change, this code would no longer compile.Even if we disregard that as 'well, if you write stupid code, I don't care that it breaks on an update' (which is a bit... aggressive, let's say), there's still the issue of implementors who can't just be silently 'upgraded': They wrote:
and given that they did not add the
@NotNullByDefaultmarker, that code is designed to assume thatamight be null. So how do we tackle this?@NotNullByDefaultis on. Yes, this works here (in that thinking aboutabeing null is rather silly, given that the spec explicitly says this should result in an NPE, i.e. - not a thing a caller should be doing), but you can't just treat every method every written like that, of course!T[]might well be null here. But that won't work - the signatures are now no longer aligned. For parameters that might be allright (if the code is written to deal with null and is used in a context where null will never be passed - so what?), but for return types it obviously isn't.The upshot is: You end up with a situation where all implementors of this interface must recompile and possibly add some nullity markers or their code is broken and no longer compiles.
For all interfaces in the entire ecosystem. All of them.
We might as well call it java 2.0 at that point.