Monday, November 21, 2011

Two Generally Useful Guava Annotations

Guava currently (Release 10) includes four annotations in its com.google.common.annotations package: Beta, VisibleForTesting, GwtCompatible, and GwtIncompatible. The last two are specific to use with Google Web Toolkit (GWT), but the former two can be useful in a more general context.

The @Beta annotation is used within Guava's own code base to indicate "that a public API (public class, method or field) is subject to incompatible changes, or even removal, in a future release." Although this annotation is used to indicate at-risk public API constructs in Guava, it can also be used in code that has access to Guava on its classpath. Developers can use this annotation to advertise their own at-risk public API constructs.

The @Beta annotation is defined as a @Documented, which means that it marks something that is part of the public API and should be considered by Javadoc and other source code documentation tools.

The @VisibleForTesting annotation "indicates that the visibility of a type or member has been relaxed to make the code testable." I have never liked having to relax type or member visibility to make something testable. It feels wrong to have to compromise one's design to allow testing to occur. This annotation is better than nothing in such a case because it at least makes it clear to others using the construct that there is a reason for its otherwise surprisingly relaxed visibility.

Conclusion

Guava provides two annotations that are not part of the standard Java distribution, but cover situations that we often run into during Java development. The @Beta annotation indicates a construct in a public API that may be changed or removed. The @VisibleForTesting annotation advertises to other developers (or reminds the code's author) when a decision was made for relaxed visibility to make testing possible or easier.

2 comments:

Unknown said...

A good article that resumes the guava annotations. A question: I've made lot of researches on the net ... no way!
A non standard (Java/JEE) annotation is subject to compilation, that is it needs something to process it! How, when and what compiles or processes the @VisibleForTesting annotation?

Thank you

@DustinMarx said...

Mahieddine,

For the specific examples covered in this blog post, you simply need to include the appropriate Guava JAR on your compilation classpath and the Java compiler will be able to handle the annotations appropriately.

Through Java SE 6, apt was the standard annotations processing tool, but apt was deprecated with Java SE 7 in favor of javax.annotation.processing (introduced with Java SE 6).