I recently spent a few days back-filling test code to help a team meet one of its its quality objectives – namely unit test coverage – and the scany level of documentation within the code re-enforced my views on properly documenting the contract of a method. The methods I wrote tests for had the minimum of JavaDoc, enough to ensure no warnings from Eclipse, but nothing beyond that. So I had an idea of what the method was supposed to do, and roughly what the arguments were for – but no indication if null was a valid value for a given argument, or what would happen if an argument value was non-null but invalid.
To write tests for the method contract I had to pick through the underlying code – far from ideal, as I’m now inferring the contract from the code, and the code may not be correct. And this particular organisation hadn’t adopted the de facto approach to validating method arguments as documented in the excellent Effective Java (recently re-issued for Java 5) by Josh Bloch.
Briefly, the method contract consists of two component parts: the explicit contract – the method name, arguments and their types, and the implicit contract – which arguments can be null, the valid range of values for a numeric argument, etc. The degree of documentation for a method and its contract should be proportional to its complexity and the level of exposure the method is likely to receive – and it doesn’t get much more exposed than a component interface, so these should be very well documented indeed. The objective is to leave no ‘wriggle room’ in the specification – either for those developing an implementation or those who might want to use it. Or indeed, test it.
By providing thorough documentation for a method you are in effect crystalising the purpose of that method. As a developer it clarifies what you are trying to achieve; for a user of the method it helps them to understand what the method does and how to use it correctly. It should also tell them what error conditions exist and therefore allow them to be catered for.
This may seem overkill for a one or two man project, and you may be justified in short-circuiting the process to an extent. However it is vital in larger projects, and putting the documentation with the method ensures that future maintainers and users of the code do not have to hunt around for supplementary documentation. Or the original author, to explain what is going on. And even for a one man project, coming back to code cold after, say, 18 months, you might just find that the documentation refreshes your memory…