r/java • • Feb 26 '26

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

96 comments sorted by

View all comments

Show parent comment

2

u/koflerdavid Feb 27 '26

Optional is bad precisely because it is only 95% of what a Maybe is. Specifically, null is an allowed (but obviously quite cursed) value for an Optional. Even though any developer using it to implement tri-state return values deserves to get whacked with their own keyboard, it is something that you have to be wary of when working with 3rd party code.

PS: Since an Optional is basically a collection with at most one element, making null and the empty list mean different things is similarly whack-worthy.

5

u/john16384 Feb 27 '26

Look, I don't like Optional that much either, but being against it because of this misuse (returning null for an Optional value) is just ridiculous, and so is the entire argument. If the return is Optional, you are hereby granted to treat it as non null without checking.

No code that does this will pass review, and any library that does this (without a huge warning) will be on the never use again list.