2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
When using null-related annotations at global scope level, for instance using ``++javax.annotation.ParametersAreNonnullByDefault++`` (from JSR-305) at package level, it means that all the parameters to all the methods included in the package will, or should, be considered Non-``++null++``. It is equivalent to annotating every parameter in every method with non-null annotations (such as ``++@Nonnull++``).
The rule raises an issue every time a parameter could be ``++null++`` for a method invocation, where the method is annotated as forbidding null parameters.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
@javax.annotation.ParametersAreNonnullByDefault
class A {
void foo() {
bar(getValue()); // Noncompliant - method 'bar' do not expect 'null' values as parameter
}
void bar(Object o) { // 'o' is by contract expected never to be null
// ...
}
@javax.annotation.CheckForNull
abstract Object getValue();
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
Two solutions are possible:
* The signature of the method is correct, and null check should be done prior to the call.
* The signature of the method is not coherent and should be annotated to allow null values being passed as parameter
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
@javax.annotation.ParametersAreNonnullByDefault
abstract class A {
void foo() {
Object o = getValue();
if (o != null) {
bar(o); // Compliant - 'o' can not be null
}
}
void bar(Object o) {
// ...
}
@javax.annotation.CheckForNull
abstract Object getValue();
}
----
or
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
@javax.annotation.ParametersAreNonnullByDefault
abstract class A {
void foo() {
bar(getValue());
}
void bar(@javax.annotation.Nullable Object o) { // annotation was missing
// ...
}
@javax.annotation.CheckForNull
abstract Object getValue();
}
----
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Annotate the parameter with @javax.annotation.Nullable in method declaration, or make sure that null can not be passed as argument
=== Highlighting
Principal: Nullable parameter expression (with flow leading to null constraint)
Secondary: method declaration (what if in other file?)
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]