Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.annotation.Nonnull vs assert

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.

like image 824
Gualtiero Testa Avatar asked Feb 11 '13 10:02

Gualtiero Testa


People also ask

What does javax annotation NonNull do?

@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.

What does @nullable mean in Java?

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 ... }

What is @nonull?

@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.

What is @CheckForNull?

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 .


2 Answers

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.

like image 81
Christophe Roussy Avatar answered Sep 22 '22 21:09

Christophe Roussy


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.

like image 34
David Lavender Avatar answered Sep 20 '22 21:09

David Lavender