I'm using Findbugs and javax.annotation.Nonnull on method parameters.
On private methods I usually add an assert line to check for nullness like
private void myMethod(@Nonnull String str) {
assert str != null
....
Latest Netbeans version (7.3rc2) is reporting that the assert check is not necessary (because of the Nonnull annotation). I'm not fully sure this is a Netbeans bug or not.
Can the assert line be removed because I specified the @Nonnull annotation ?
As far as I understand, the annotation is used only during static analysis while assert is, when enabled, active during execution so the twos are not alternative.
@NotNull The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
The @NonNull/@Nullable annotation can put in front of functions as well to indicate the return value nullability. @NonNull. public A getA() { return null; // warn: 'null' is returned by the method ... }
@Nonnull annotation just emphasises that null-verification of the argument is on your side (you have to guarantee that you pass non-null value). It is not the responsibility of the method.
CheckForNull is meant to indicate that a returned value could be null in some cases and thus requires special handling. I know it could be added to "nullable annotations" as described on the help page: https://www.jetbrains.com/help/idea/2017.1/nullable-and-notnull-annotations.html .
The assert is evaluated at runtime, the annotation helps FindBugs catch problems during the analysis before runtime. As both checks are not really conflicting you could keep them both. I would find it annoying if my IDE told me to remove the assert.
Netbeans is right. If you think it can be null: remove the annotation. If you know it can't: remove the assert.
If there's ANY chance that your method could be called with a null value, then @Nonnull
annotation shouldn't be there.
Like you said, that annotation doesn't actually do anything at runtime: it is only used by IDEs and static code analysis tools. It doesn't ensure that things aren't null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With