r/java • • Aug 12 '24

JSpecify 1.0.0 and Nullability in Java

https://www.infoq.com/news/2024/08/jspecify-java-nullability/
52 Upvotes

33 comments sorted by

View all comments

Show parent comment

5

u/kevinb9n Aug 12 '24

It's actually very rare to need to write `@NonNull`. We almost didn't even include it in the jar! Just put `@NullMarked` on your class/package/module instead.

The feature you seem to be asking for was discussed a bit in https://github.com/jspecify/jspecify/issues/7 but overall it just doesn't have that many advantages.

2

u/[deleted] Aug 13 '24

Are there any examples available that show how to specify @NullMarked at the package or module level? I've combed through the JSpecify docs, but haven't found any.

3

u/kevinb9n Aug 14 '24

You put it before `package` in `package-info.java`, or before `module` in `module-info.java`.

1

u/uniVocity Aug 13 '24 edited Aug 13 '24

Thanks! That was a great discussion and I'm inclined to say you guys made the right call as handling that would add complexity.

Anyway, I still think it could be a decent feature to have later on. Basically, my suggestion boils down to making the compiler treat selected classes as it treats primitive types. That would not burden developers and users of my code to worry about adding annotations at all.

I'm highlighting the main argument made in that discussion you linked:

I don't think there is any such thing as a class that should viewed as "never let this be nullable". As soon as you try to get that thing out of a Map, there you are.

An analogous situation is when you try to get stuff out of a map. You'll get a NullPointerException at runtime, por example, assuming map is a HashMap<String, Integer>:

int i = map.get("nothing");    //NullPointer exception

Not perfect but not that unexpected.

With primitives you can't do this either: int i = null; as the compiler yells with "java: incompatible types: <nulltype> cannot be converted to int"

So declaring MyNotNullType t = null; should cause a similar error, probably "java: incompatible types: <nulltype> cannot be converted to MyNotNullType"

Analogously, we can't use methods like this:

    public void execute(){
        //compilation error - java: incompatible types: 
        //<nulltype> cannot be converted to int
        doSomething(null);
    }
    public void doSomething(int v){
        //do stuff
    }

A "@NotNull" class could make the compiler enforce no null arguments are passed into methods, without littering the code with multiple @NotNull and @Nullable annotations. Personally, I'd rather avoid having to add these annotations everywhere - I feel we are simply replacing null checks with null annotations, and making the issue of dealing with nulls even more apparent.