Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it required to use annotation on implementation when already specified at interface

I am thinking to use @Nonnull annotation provided in javax.annotaiton.Nonnull which has retention policy as runtime. With this annotation I want to ensure that null is never returned by this function. I would like to put the annotation on interface so that no future implementations breaks existing code as follows

public interface X {
    @Nonnull public List<A> func();
}

Now what I do not understand is that should I use the same annotation on the implementation as well. So which one of the following is would be the correct way to write the implementation of this interface (both of these compile):

public class XImpl implements X {
    @Override
    @Nonnull public List<A> func() {
         //code
    }
}

Or

public class XImpl implements X {
    @Override
    public List<A> func() {
         //code
    }
}
like image 737
Aman Deep Gautam Avatar asked Dec 24 '14 13:12

Aman Deep Gautam


1 Answers

Ordinarily, you should look at the annotation's documentation. Unfortunately, the javax.annotation.Nonnull annotation contains no documentation (!). The annotation was proposed by JSR 305, but JSR 305 has since been abandoned. JSR 305 didn't give a semantics and didn't give a reference implementation.

You will want to process the annotation with some tool, such as the Checker Framework or FindBugs. In order to understand whether to write the annotation on an implementation in addition to on an interface, you will need to look at the documentation for the tool.

The Checker Framework manual says that you need to write the annotation on the implementation as well as on the interface. This gives better documentation, since you can understand the implementation on its own without having to also read the interface.

The FindBugs manual doesn't contain the words "inherit" nor "inheritance", and messages to the mailing list about annotations and inheritance were not answered. FindBugs does treat some annotations, such as CheckReturnValue, as inherited, but you seem to have no guarantee about the current or future behavior of @Nonnull. I recommend writing the annotation explicitly, which should be safe and has the documentation benefits noted above.

like image 57
mernst Avatar answered Sep 21 '22 14:09

mernst