Chapter 46. Kinds of Comments
Nicolai Parlog
Assume you want to put some comments into your Java code. Do you use /**, /*, or //? And where exactly do you put them? Beyond syntax, there are established practices that attach semantics to which is used where.
Javadoc Comments for Contracts
Javadoc comments (the ones enclosed in /** ... */) are exclusively used on classes, interfaces, fields, and methods and are placed directly above them. Here is an example from Map::size:
/** * Returns the number of key-value mappings in this map. If the * map contains more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of key-value mappings in this map */ int size();
The example demonstrates syntax as well as semantics: a Javadoc comment is a contract. It promises API users what they can expect while keeping the type’s central abstraction intact by not talking about implementation details. At the same time, it binds implementers to provide the specified behavior.
Java 8 relaxed this strictness a little while formalizing different interpretations by introducing the (nonstandardized) tags @apiNote, @implSpec, and @implNote. The prefixes, api or impl, specify whether the comment addresses users or implementers. The suffixes, Spec or Note, clarify whether this is actually a specification or only for illustration. Notice how @apiSpec is missing? That’s because ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access