How to document (simple) preconditions of a Java method?
You can create custom javadoc tags, i.e. @pre
@inv
and @post
for precondition, invariant and postcondition.
Further, Joshua Bloch argues in Effective Java Second Edition:
The doc comment should enumerate all of the method's preconditions, which are the things that have to be true in order for a client to invoke it, and its postconditions Typically, preconditions are described implicitly by the
@throws
tags for unchecked exceptions; each unchecked exception corresponds to a precondition violation. Also, preconditions can be specified along with the affected parameters in their@param
tags.
Examples:
/** * @param index index of element to return; must be non-negative and less * than the size of this list * @throws IndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= this.size()}) */
Note, that every exceptions begins with if, followed by a clause describing the conditions under which the exception is thrown. (precondition) This is often described with arithmetic expressions.
You seem hesitant to rely on your API's Javadocs to provide exactly that: documentation for your API. While I agree some developers will invariably ignore its warnings, I think historically Javadocs have been entirely adequate in providing sufficient guidance on how to correctly use an API. You can go crazy creating all kinds of custom Annotation
s, but in the end people will still implement your API incorrectly at times.
If you did want to go even further beyond what you already have there, you could also implement self-documenting naming conventions wherever practical. For example:
/**
* Foos a positive bar.
* @param positiveBar the non-zero,non-negative bar to be food
* @throws IllegalArgumentException if bar is zero or negative
*/
public void foo(int positiveBar) {
...
Lastly, although your question is about how to document these constraints and not handle them, I will say to not underestimate the value of IllegalArgumentException
. This is precisely what it should be used for and engineers should not be afraid to throw this exception to indicate a programming error. Developers aren't going to get far without reading the docs when their implementation doesn't run.