Sunday, January 23, 2011

Javadoc - the “Why” of your code.


Code should not need to be figured out, it should be just read. -Martin Fowler

How do you express a not thread safe method? That null is not a valid parameter? That if you call a method in an object, the object will be in a different state? How do you communicate ownership of parameters?

In Java, some of these points are handle trough meta-data using annotations, throwing Exceptions, etc. Nevertheless there is a limit on how well it communicate intent, There is still a gap between the “How” and the “Why” of your code. For example you can declare the exceptions thrown by a method, but you can not fully communicate the why without the documentation, without the javadoc.

Java have limitations to communicate in code all that there is to say about the behavior of the program. Different languages, like Eiffel, provide more mechanism where you can define pre conditions, post conditions and invariants on the objects with the code itself. In Clojure the data structures are value object therefore there is no need to define the ownership of parameters you will always get something new. But even in those languages, there is a need to document - to express the "why" of your code, the reason behind your design, examples on how to use it or how to extend the code.

Joshua Bloch in "How to Design a Good API & Why it Matters" mention his rules about documentation which I use as guide lines:

Document Religiously
  • Document every class, interface, method, constructor, parameter, and exception.
  • Class: what an instance represents.
  • Method: contract between method and its client.
  • Preconditions, postconditions, side-effects.
  • Parameter: indicate units, form, ownership.
  • Document state space very carefully

Even when programming by intention or with languages that communicate better we still need documentation. Without the extra information provided by documentation future programmers have to guess about the missing documented behavior, ghosts side effects. That's why I encourage good documentation among my peers programmers.

"Reuse is something that is far easier to say than to do. Doing it requires both good design and very good documentation. Even when we see good design, which is still infrequently, we won't see the components reused without good documentation."
- D. L. Parnas, _Software Aging. Proceedings
of 16th International Conference Software
Engineering, 1994