JavaDoc for private / protected methods? [closed]

Should I write JavaDoc for private or protected methods? And what about private variables?

I see class examples on my Java book and the private variables are JavaDoc'ed. So I can't understand if it is a good practice to JavaDoc the private (or protected) methods.


Solution 1:

Yes you should write JavaDoc for private methods, and even when it is only for yourself. In 3 years when you have to change the code, you will be happy that you documented it.

If you leave the company, or have to work on another project, your co-workers will be happy to have a documented code. Undocumented code has much lower value.

And look how the real professionals do it. Here is an excerpt from the source code of ArrayList class by Sun Microsystems:

 /**
  * The array buffer into which the elements of the ArrayList are stored.
  * The capacity of the ArrayList is the length of this array buffer.
  */
  private transient Object[] elementData;

Solution 2:

The first question you need to ask yourself is "why write JavaDocs at all?" Who are they useful for? Who asked you to write them?

Most likely, someone (employer / professor) asked you to document some of your methods. This is generally A Good Thing, but comes with a cost: additional maintenance.

If you have a publicly accessible version of your docs (such as if you're generating them and publishing them online for end-users), it makes sense to document anything your end users will need to know. This includes all public classes and methods.

What about for yourself, and other developers?

My opinion is that you shouldn't use javadocs on internal and private methods and classes. The main reason is that javadocs primarily benefit people who consume, not maintain, your code.

On the other hand, you do need to keep notes and comments on your own code, which is often internal. In this case, I would suggest normal comments (eg. //) instead; it's less maintenance, and often, equally clear, with a lot less typing.

On the other hand, if a method becomes public, it can be useful to convert those comments into a true javadocs. Javadocs have the benefit of forcing you to think about (and document) every parameter, exception, and return value.

The trade-off is yours to make.

Solution 3:

Nope, you shouldn't write javadoc for private methods. End users don't have access to private fields or methods so there really isn't a point in providing javadoc for them. Private fields and methods are only meant for the developer. If you really need to though, feel free to write comments for non-obvious logic. You should probably write javadoc for protected methods because these methods are sometimes overridden and it is helpful to provide the user with some information about what the method does, or, should do.