It is often the case that a method imposes constraints on its arguments that cannot be described by the type system. For example, a method might require that some argument be non-null, or some int-typed argument be positive. There might also be more complex preconditions, for example that a certain method was called before, or that a certain object is in some state. What is the best way to document this in Javadoc?
For example, suppose I have the following public library function, where the argument cannot be negative:
public void foo(int bar) {
if (bar < 0) {
throw new IllegalArgumentException("Negative bars cannot be food.");
}
...
}
I want to document this in such a way that it "stands out" from the rest of the documentation text so that documentation readers know immediately where they have to look. Currently, I do this by adding throws
clauses to the Javadoc:
/**
* Foos a bar.
* @param bar the bar to be food
* @throws IllegalArgumentException if bar is negative
*/
public void foo(int bar) {
...
However, this introduces the throwing of the exception into the specification of the method. Now, library users might depend on this behavior in their code. So if I want to change the method in a next version in such a way that also negative parameters are allowed, I might break clients' code.
Are there any best practices to document things like this in Javadoc? I have thought of:
- Describing in the documentation text that the method has undefined behavior if the argument is negative. However, this does not really stand out, so it might be missed by a lot of library users.
- Using annotations (
public void foo(@NonNegative int bar)
). However, for this a standard set of annotations would be ideal, and this standard set does not appear to exist.