You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[moved to #230] Decide whether to include a @NonNull annotation #4
We use the Checker Framework inside Google. The CF defaults to non-null, i.e. if an element is not annotated, it is assumed to be @NonNull. I think cpovirk is asking whether we can do that in this project as well.
IntelliJ IDEA has an option to add a runtime assertion whenever there's something @NotNull-annotated. This works fine with explicit annotations, but not too well with defaults (scoped or not). I wonder if people will expect runtime instrumentation to be added if the default is non-null. This would be problematic because it'd depend on whether the project is using these annotations or not, and it might be not easy to tell.
Currently IntelliJ IDEA can only generate runtime assertions (which are quite useful) when @NotNull is specified locally. Honoring default package-level not-nulls is a challenge, because if one appears or disappears, the IDE has to detect that and recompile the whole package.
In our last discussion, the decision whether something is annotated or not is purely based on whether there is a NotNullByDefault (TBD) annotation on the enclosing top-level class or directly enclosing package.
Having @NotNull as an explicit annotation is still useful. In addition to the examples above, it can be useful to suppress warnings and pick an explicit annotation.
It's largely about flipping the default, but it sort of goes deeper because it means more cases for users to understand (and us to make sure that we're getting right).
The main concrete example I have is the "overrides"/"projects" example. Granted, a large part of that idea still needs to exist no matter what: It's always possible to have @Nullable T (like Map.get()). But to me, it feels easier to understand "It's possible to add null to the permissible values" than "It's possible to add or remove null." I mean, it sounds simple, but then I start trying to think about how @NullnessUnknown plays into all this, and I really don't want to have to think about 3x3 cases instead of 2x2.
(I should also acknowledge that there's some case, which is escaping me at the moment, in which @NotNull is "necessary." But IIRC it's only because the bounds aren't following PECS -- though I think they can't in that case for some reason, but the point is that the signature is already "broken" before nullness gets involved. Plus, handling this one usual case feels like the tail wagging the dog. Sorry for being so vague; I can pull up details if we discuss later.
Because of the name, I'd been thinking that the use case was Map.getOrDefault, but I was wrong.
I can believe that someone does want this somewhere, but I'd expect it to be rare.
I searched our code base for usage [^<]@NonNull\b\s*[A-Z]\b -- basically, example of @NotNull T. I looked at the first few ~30 results, and I was not impressed: As expected, it's almost exclusively code that could be trivially converted to declare the type parameter itself as @NotNull. Declaring the type parameter itself as @NotNull is both better (since it will allow the code to use, say, an Optional<T> [edit: rather than needing to project to Optional<@NotNull T>]) and, with our proposed defaulting rules, easier (since, unlike the Checker Framework, <T> will mean <T extends [@NotNull] Object rather than <T extends @Nullable Object>) [edit: disputed in #12]
I did see one instance of <E extends Enum<E>>. I'm not sure if we'll allow <E extends [@NotNull] Enum<E>>, so maybe there's a use case there?
Another speculative(?) use case that @kevinb9n had raised is in specifying a nullness for type parameters with unknown nullness:
[@DefaultNullnessUnknown]
classSomeForeignList<E> {
Eget(inti);
}
@DefaultNotNullclassMyClass<E> {
// Checkers might *require* a nullness annotation here, where it would mean// to treat E as if it had been declared as <E extends @NotNull Object>.SomeForeignList<@NotNullE> delegate;
}
There might be a need for this, but:
I have been feeling that operating with type parameters of unknown nullness is just going to be too messy, and people should define stubs or leave the nullness unknown.
This feels like a very, very different meaning than @NotNull normally has. If we need to support it (see (1) :)), then it may deserve its own annotations. [edit: Or possibly @NotNull doesn't have much effect here, since SomeForeignList.get(i) is still treated as returning @NullnessUnknown E?]
One other point:
Providing @Nullable but not @NotNull is (IIUC) a better match for the types declarable in Kotlin source. That should help programmers move from one language to the other -- and presumably help code be converted, too. (I wonder if @NotNull could even complicate Kotlin's ability to interpret these nullness annotations, but I haven't tried to reason through that.)
(I also said above the the signature is already "broken." I think I was wrong about that, too, sorry: I believe my point was that the method should really return <U super T>, so you could call fooOfDouble.getOrDefault(1) and get back a Number. But that doesn't help with adding @NotNull, which would a <U extends T> type (which doesn't make sense here).)
so compilers can insert the annotation automatically (kotlinc does this, for instance).
Could they automatically insert @DefaultNotNull and then insert @Nullable where needed? As noted above, this seems like a closer match to the Kotlin model, so if anything, I would hope that it would be easier.
I think it's important to have @NotNull so checkers can distinguish unannotated code from annotated-but-defaulted-to-@NotNull code.
I think this is solved now by having annotations like @DefaultNotNull and @DefaultNullnessUnknown (with the latter as the "default default"), right?
In addition to the examples above, it can be useful to suppress warnings and pick an explicit annotation.
I'm not sure I understand. Can you elaborate? Is this about explicitly specifying nullness on a local variable, whose nullness would otherwise be inferred? (If so, would we prefer an explicit test (e.g., requireNonNull) to a suppression? Might we require a suppression in any case?)
Currently IntelliJ IDEA can only generate runtime assertions (which are quite useful) when @NotNull is specified locally. Honoring default package-level not-nulls is a challenge, because if one appears or disappears, the IDE has to detect that and recompile the whole package.
This should also be solved now that we are planning not to support per-package defaults.
Providing @Nullable but not @NotNull is (IIUC) a better match for the types declarable in Kotlin source. That should help programmers move from one language to the other -- and presumably help code be converted, too. (I wonder if @NotNull could even complicate Kotlin's ability to interpret these nullness annotations, but I haven't tried to reason through that.)
This probably applies to other languages, too.
For example, we discussed this morning how Scala 3 is talking about supporting null using union types (Foo | Null). This makes it (possibly?) easy to model @Nullable T. But it's less clear that they'd have a way to model @NotNull T (barring support for set difference, which I suppose is possible -- oh, or maybe they can just intersectT with Any or AnyRef or something? Most languages won't have as many features as Scala to fall back on, though).
And if Java itself were to gain built-in nullability support, we don't know if they'd want to build in support for the equivalent of @NotNull T, especially given that they'd likely need to support it in their user-facing APIs [edit: meaning reflection and annotation-processing APIs] (though maybe that doesn't end up as hard as I'd think) and they'd know that other Java tools might not handle it correctly.
Now of course we've accepted soundiness, so it's probably OK if not every user of our annotations handles them completely. But I think the even better soundiness argument is that, if @NotNull T would be needed only rarely, then we don't need it at all :) It would be especially sad if some tools didn't implement @NotNull T correctly and therefore couldn't check code when that code shouldn't have used @NotNull T in the first place :)
Currently, IntelliJ IDEA codebase doesn't use the default annotations, and default nullability of all methods is really unknown. For some non-annotated interface method without checking all the implementation, one cannot tell whether the null return or parameter is possible. We have dozens of thousands of method parameters which are annotated as NotNull, but also dozens of thousands of non-annotated method parameters. Changing to DefaultNotNull would be a big pain for our project because we will need to explicitly annotate every non-annotated method parameter and return value as @NullnessUnknown (at least until we figure out the actual nullability of every parameter and return value). So for our project migrating to the annotations package which doesn't provide a @NotNull annotation is not an option. I could agree that our codebase is a mess, but don't expect that most real-world Java code is in the better shape. After all, the high adoption of our project is one of the primary goals. Absence of @NotNull clearly goes against.
We may create some official guidelines or a tutorial on how to start a new project with our annotations where we may discourage the @NotNull usage, suggesting that it should be used in exceptional cases only. We may even mention it in the @NotNull JavaDoc. In general, I agree that in the new project the @NotNull annotation is not that necessary. However, if you migrate an existing project, this may vary.
I'm quite willing to believe this is not a case that comes up in a lot of APIs, but it's still an important one for users, since these particular APIs, as you were able to confirm, are unsurprisingly used a lot.
Here's a related example this brings to mind (Javadoc):
list.removeIf(Objects::isNull)
Really capturing this would require "changing" list's type argument. I'm not sure I've seen a tool that can express this, though it's seemingly doable in principle.
Another thing that libraries could conceivably do is to add methods like filter(Class), similar to what FluentIterable has. This would naturally return a Sequence<T> for some non-null type T.
But there are significant downsides:
It works only if you have a Class object. That's easy if you're operating on, say, a Stream<String>, but it's inconvenient or impossible if you have to handle a generic Stream<T>.
It's possible to pass the wrongClass object, and you get a mysteriously empty stream. (Probably Error Prone could help if such an API were added. I guess it could help with FluentIterable today if we wanted to write a check.)
It's more code.
It's much less clear about what it's doing. ("Why is it filtering a Stream<Foo> for instances of Foo?") It's even possible that people would expect filter(String.class) to keep null values (though that might be a stretch, and of course nullness annotations would help clear that up).
Also, the JDK was not interested. It's conceivable that nullness could make them feel differently, but if they were making a change specifically for nullness, then filterNonNull might make sense -- if it were expressible, which I still sort of doubt would be the case for a nullness language feature, even if it is with our annotations.
Explaining, convincingly, that there is actually a reasonably sane world in which @NonNull does not exist in our project. (This step is NOT convincing anyone to like that world, just that it does fundamentally make sense.)
Explaining the benefits and the drawbacks of having a @NonNull annotation relative to that picture. Warning: we have so far come up with about TEN arguments on each side. We are working to distill that morass down into something consumable for you. If you are keen to have it shared to you before then, let me know.
For a long time, I believed there was really no controversy to be had here; of course we would need @NonNull. I was dead wrong: while we may want it, there really is a case to be made either way, and our sacred duty is to fully explore both sides.
We've been talking about an initial 0.1 pre-release that supports only the use cases of (a) fully, properly annotated source files and (b) all-legacy source files, but nothing in between. (Of course, that fails a key project requirement, which is why it's not called 1.0.) Also, support for non-nullable type projections would come later as well (if at all; #86). If our working decisions on issues like #12 go the way the currently seem to be, then this means that we would not actually have much need for @NonNull for this 0.1 release yet no matter which way we end up deciding here.
Hopefully that means the time pressure is a little reduced on making this decision.
changed the title [-]Is there still any chance of skipping @NonNull entirely?[/-][+]Decide whether to include a `@NonNull` annotation[/+]on May 11, 2020
We can't really avoid @Nullable on the interface or superclass because we want to be defensive and force null-safety checks when they are used, and only skip those when the specific subclass annotated with @NonNull is used.
I guess we can live with 16 warnings in 0.1 release, but we would like a proper solution that allows 0 warnings after.
Thanks: I am embarrassed to discover that, as far as I can tell, I had not searched through Spring for usages of @NonNull.
For the 16 that you have, all would be unnecessary under jspecify semantics: Our annotations aren't automatically inherited by overrides, so overriding @Nullable Foo getParameterNames() with Foo getParameterNames() already makes the return of the latter non-null.
Our recent discussions about sample inputs remind me that I should add some samples for this case. I'll try to come back and link them from this post once I've done so.
(Of course, in all this, I'm assuming that you apply @DefaultNonNull (or make your @NonNullApi an alias for it), since your files are fully annotated. The big use case for @NonNull is for code that does not use @DefaultNonNull. We have been preparing some giant docs for the eventual discussion :))
kevinb9n suggested that we close this thread in favor of a new one -- not with the intention of having this discussion tomorrow but at least to give interested parties a rough idea of the areas of past conversation.
When we're ready to make a decision, we'll clean up and old, unpublished doc we have about this -- or throw it out and write a new one, too :) But for a quick summary, see #230.
changed the title [-]Decide whether to include a `@NonNull` annotation[/-][+][moved to #229] Decide whether to include a `@NonNull` annotation[/+]on Jan 31, 2022
changed the title [-][moved to #229] Decide whether to include a `@NonNull` annotation[/-][+][moved to #230] Decide whether to include a `@NonNull` annotation[/+]on Feb 2, 2022
Activity
eaftan commentedon Nov 26, 2018
We use the Checker Framework inside Google. The CF defaults to non-null, i.e. if an element is not annotated, it is assumed to be
@NonNull. I think cpovirk is asking whether we can do that in this project as well.donnerpeter commentedon Nov 26, 2018
IntelliJ IDEA has an option to add a runtime assertion whenever there's something
@NotNull-annotated. This works fine with explicit annotations, but not too well with defaults (scoped or not). I wonder if people will expect runtime instrumentation to be added if the default is non-null. This would be problematic because it'd depend on whether the project is using these annotations or not, and it might be not easy to tell.kevin1e100 commentedon Dec 20, 2018
I think @NotNull will be rarely used in Java source code, but I do think it's valuable to have it for a few cases:
donnerpeter commentedon Dec 20, 2018
Currently IntelliJ IDEA can only generate runtime assertions (which are quite useful) when
@NotNullis specified locally. Honoring default package-level not-nulls is a challenge, because if one appears or disappears, the IDE has to detect that and recompile the whole package.eaftan commentedon Dec 20, 2018
I think it's important to have
@NotNullso checkers can distinguish unannotated code from annotated-but-defaulted-to-@NotNullcode.wmdietlGC commentedon Jan 10, 2019
In our last discussion, the decision whether something is annotated or not is purely based on whether there is a NotNullByDefault (TBD) annotation on the enclosing top-level class or directly enclosing package.
Having
@NotNullas an explicit annotation is still useful. In addition to the examples above, it can be useful to suppress warnings and pick an explicit annotation.kevinb9n commentedon May 1, 2019
I concur that we are going to need @NotNull. I think we can probably close this?
kevinb9n commentedon Jun 27, 2019
From @cpovirk
It's largely about flipping the default, but it sort of goes deeper because it means more cases for users to understand (and us to make sure that we're getting right).
The main concrete example I have is the "overrides"/"projects" example. Granted, a large part of that idea still needs to exist no matter what: It's always possible to have
@Nullable T(like Map.get()). But to me, it feels easier to understand "It's possible to add null to the permissible values" than "It's possible to add or remove null." I mean, it sounds simple, but then I start trying to think about how @NullnessUnknown plays into all this, and I really don't want to have to think about 3x3 cases instead of 2x2.(I should also acknowledge that there's some case, which is escaping me at the moment, in which @NotNull is "necessary." But IIRC it's only because the bounds aren't following PECS -- though I think they can't in that case for some reason, but the point is that the signature is already "broken" before nullness gets involved. Plus, handling this one usual case feels like the tail wagging the dog. Sorry for being so vague; I can pull up details if we discuss later.
cpovirk commentedon Jul 1, 2019
Following up:
The case where
@NotNullis necessary is actually (to the best of my knowledge) hypothetical:Because of the name, I'd been thinking that the use case was
Map.getOrDefault, but I was wrong.I can believe that someone does want this somewhere, but I'd expect it to be rare.
I searched our code base for usage
[^<]@NonNull\b\s*[A-Z]\b-- basically, example of@NotNull T. I looked at the first few ~30 results, and I was not impressed: As expected, it's almost exclusively code that could be trivially converted to declare the type parameter itself as@NotNull. Declaring the type parameter itself as@NotNullis both better (since it will allow the code to use, say, anOptional<T>[edit: rather than needing to project toOptional<@NotNull T>]) and, with our proposed defaulting rules, easier (since, unlike the Checker Framework,<T>will mean<T extends [@NotNull] Objectrather than<T extends @Nullable Object>) [edit: disputed in #12]I did see one instance of
<E extends Enum<E>>. I'm not sure if we'll allow<E extends [@NotNull] Enum<E>>, so maybe there's a use case there?Another speculative(?) use case that @kevinb9n had raised is in specifying a nullness for type parameters with unknown nullness:
There might be a need for this, but:
I have been feeling that operating with type parameters of unknown nullness is just going to be too messy, and people should define stubs or leave the nullness unknown.
This feels like a very, very different meaning than
@NotNullnormally has. If we need to support it (see (1) :)), then it may deserve its own annotations. [edit: Or possibly@NotNulldoesn't have much effect here, sinceSomeForeignList.get(i)is still treated as returning@NullnessUnknown E?]One other point:
Providing
@Nullablebut not@NotNullis (IIUC) a better match for the types declarable in Kotlin source. That should help programmers move from one language to the other -- and presumably help code be converted, too. (I wonder if@NotNullcould even complicate Kotlin's ability to interpret these nullness annotations, but I haven't tried to reason through that.)(I also said above the the signature is already "broken." I think I was wrong about that, too, sorry: I believe my point was that the method should really return
<U super T>, so you could callfooOfDouble.getOrDefault(1)and get back aNumber. But that doesn't help with adding@NotNull, which would a<U extends T>type (which doesn't make sense here).)cpovirk commentedon Jul 1, 2019
Could they automatically insert
@DefaultNotNulland then insert@Nullablewhere needed? As noted above, this seems like a closer match to the Kotlin model, so if anything, I would hope that it would be easier.I think this is solved now by having annotations like
@DefaultNotNulland@DefaultNullnessUnknown(with the latter as the "default default"), right?I'm not sure I understand. Can you elaborate? Is this about explicitly specifying nullness on a local variable, whose nullness would otherwise be inferred? (If so, would we prefer an explicit test (e.g.,
requireNonNull) to a suppression? Might we require a suppression in any case?)This should also be solved now that we are planning not to support per-package defaults.
cpovirk commentedon Jul 18, 2019
This probably applies to other languages, too.
For example, we discussed this morning how Scala 3 is talking about supporting null using union types (
Foo | Null). This makes it (possibly?) easy to model@Nullable T. But it's less clear that they'd have a way to model@NotNull T(barring support for set difference, which I suppose is possible -- oh, or maybe they can just intersectTwithAnyorAnyRefor something? Most languages won't have as many features as Scala to fall back on, though).And if Java itself were to gain built-in nullability support, we don't know if they'd want to build in support for the equivalent of
@NotNull T, especially given that they'd likely need to support it in their user-facing APIs [edit: meaning reflection and annotation-processing APIs] (though maybe that doesn't end up as hard as I'd think) and they'd know that other Java tools might not handle it correctly.Now of course we've accepted soundiness, so it's probably OK if not every user of our annotations handles them completely. But I think the even better soundiness argument is that, if
@NotNull Twould be needed only rarely, then we don't need it at all :) It would be especially sad if some tools didn't implement@NotNull Tcorrectly and therefore couldn't check code when that code shouldn't have used@NotNull Tin the first place :)amaembo commentedon Aug 2, 2019
Currently, IntelliJ IDEA codebase doesn't use the default annotations, and default nullability of all methods is really unknown. For some non-annotated interface method without checking all the implementation, one cannot tell whether the null return or parameter is possible. We have dozens of thousands of method parameters which are annotated as NotNull, but also dozens of thousands of non-annotated method parameters. Changing to DefaultNotNull would be a big pain for our project because we will need to explicitly annotate every non-annotated method parameter and return value as
@NullnessUnknown(at least until we figure out the actual nullability of every parameter and return value). So for our project migrating to the annotations package which doesn't provide a@NotNullannotation is not an option. I could agree that our codebase is a mess, but don't expect that most real-world Java code is in the better shape. After all, the high adoption of our project is one of the primary goals. Absence of@NotNullclearly goes against.We may create some official guidelines or a tutorial on how to start a new project with our annotations where we may discourage the
@NotNullusage, suggesting that it should be used in exceptional cases only. We may even mention it in the@NotNullJavaDoc. In general, I agree that in the new project the@NotNullannotation is not that necessary. However, if you migrate an existing project, this may vary.42 remaining items
kevin1e100 commentedon Jan 29, 2020
Re
filtersee also: typetools/checker-framework#1345I'm quite willing to believe this is not a case that comes up in a lot of APIs, but it's still an important one for users, since these particular APIs, as you were able to confirm, are unsurprisingly used a lot.
Here's a related example this brings to mind (Javadoc):
list.removeIf(Objects::isNull)Really capturing this would require "changing"
list's type argument. I'm not sure I've seen a tool that can express this, though it's seemingly doable in principle.cpovirk commentedon Jan 29, 2020
Thanks for the link.
Another thing that libraries could conceivably do is to add methods like
filter(Class), similar to whatFluentIterablehas. This would naturally return aSequence<T>for some non-null typeT.But there are significant downsides:
Classobject. That's easy if you're operating on, say, aStream<String>, but it's inconvenient or impossible if you have to handle a genericStream<T>.Classobject, and you get a mysteriously empty stream. (Probably Error Prone could help if such an API were added. I guess it could help withFluentIterabletoday if we wanted to write a check.)Stream<Foo>for instances ofFoo?") It's even possible that people would expectfilter(String.class)to keep null values (though that might be a stretch, and of course nullness annotations would help clear that up).Also, the JDK was not interested. It's conceivable that nullness could make them feel differently, but if they were making a change specifically for nullness, then
filterNonNullmight make sense -- if it were expressible, which I still sort of doubt would be the case for a nullness language feature, even if it is with our annotations.cpovirk commentedon Feb 20, 2020
(A digression, but: I see that NullAway has special handling for the
filtercase.)kevinb9n commentedon May 8, 2020
Here is what we are working on:
Explaining, convincingly, that there is actually a reasonably sane world in which
@NonNulldoes not exist in our project. (This step is NOT convincing anyone to like that world, just that it does fundamentally make sense.)Explaining the benefits and the drawbacks of having a
@NonNullannotation relative to that picture. Warning: we have so far come up with about TEN arguments on each side. We are working to distill that morass down into something consumable for you. If you are keen to have it shared to you before then, let me know.For a long time, I believed there was really no controversy to be had here; of course we would need
@NonNull. I was dead wrong: while we may want it, there really is a case to be made either way, and our sacred duty is to fully explore both sides.We've been talking about an initial 0.1 pre-release that supports only the use cases of (a) fully, properly annotated source files and (b) all-legacy source files, but nothing in between. (Of course, that fails a key project requirement, which is why it's not called 1.0.) Also, support for non-nullable type projections would come later as well (if at all; #86). If our working decisions on issues like #12 go the way the currently seem to be, then this means that we would not actually have much need for
@NonNullfor this 0.1 release yet no matter which way we end up deciding here.Hopefully that means the time pressure is a little reduced on making this decision.
[-]Is there still any chance of skipping @NonNull entirely?[/-][+]Decide whether to include a `@NonNull` annotation[/+]sdeleuze commentedon Aug 18, 2020
FYI we have 16 concrete use cases of
@NonNullin Spring Framework codebase which is (a) fully, properly annotated source files. The use case is to avoid unnecessary checks on a subclass that returns for sure a non-nullable value whereas the interface or the superclass define@Nullable. For example https://github.com/spring-projects/spring-framework/blob/a11a592734b4518332239425973cf11cb4f80fcf/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSource.java#L169.We can't really avoid
@Nullableon the interface or superclass because we want to be defensive and force null-safety checks when they are used, and only skip those when the specific subclass annotated with@NonNullis used.I guess we can live with 16 warnings in 0.1 release, but we would like a proper solution that allows 0 warnings after.
cpovirk commentedon Aug 18, 2020
Thanks: I am embarrassed to discover that, as far as I can tell, I had not searched through Spring for usages of
@NonNull.For the 16 that you have, all would be unnecessary under jspecify semantics: Our annotations aren't automatically inherited by overrides, so overriding
@Nullable Foo getParameterNames()withFoo getParameterNames()already makes the return of the latter non-null.Our recent discussions about sample inputs remind me that I should add some samples for this case. I'll try to come back and link them from this post once I've done so.
Edit: Samples are in 149f3df...d068c45
(Of course, in all this, I'm assuming that you apply
@DefaultNonNull(or make your@NonNullApian alias for it), since your files are fully annotated. The big use case for@NonNullis for code that does not use@DefaultNonNull. We have been preparing some giant docs for the eventual discussion :))cpovirk commentedon Jan 31, 2022
kevinb9n suggested that we close this thread in favor of a new one -- not with the intention of having this discussion tomorrow but at least to give interested parties a rough idea of the areas of past conversation.
When we're ready to make a decision, we'll clean up and old, unpublished doc we have about this -- or throw it out and write a new one, too :) But for a quick summary, see #230.
[-]Decide whether to include a `@NonNull` annotation[/-][+][moved to #229] Decide whether to include a `@NonNull` annotation[/+][-][moved to #229] Decide whether to include a `@NonNull` annotation[/-][+][moved to #230] Decide whether to include a `@NonNull` annotation[/+]