Java – Self-Documenting Code vs Javadocs

documentationjavajavadocsrefactoring

Recently I've been working on refactoring parts of the code base I'm currently dealing with – not only to understand it better myself, but also to make it easier for others who are working on the code.

I tend to lean on the side of thinking that self-documenting code is nice. I just think it's cleaner and if the code speaks for itself, well… That's great.

On the other hand we have documentation such as javadocs. I like this as well, but there's a certain risk that comments here gets outdated (as well as comments in general of course). However, if they are up-to-date they can be extremely useful of say, understanding a complex algorithm.

What are the best practices for this? Where do you draw the line between self-documenting code and javadocs?

Best Answer

Self-documenting code (and in-code comments) and Javadoc comments have two very different target audiences.

The code and comments that remain in the code file are for developers. You want to address their concerns here - make it easy to understand what the code does and why it is the way it is. The use of appropriate variable names, methods, classes, and so on (self-documenting code) coupled with comments achieves this.

Javadoc comments are typically for users of the API. These are also developers, but they don't care about the system's internal structure, just the classes, methods, inputs, and outputs of the system. The code is contained within a black box. These comments should be used to explain how to do certain tasks, what the expected results of operations are, when exceptions are thrown, and what input values mean. Given a Javadoc-generated set of documentation, I should fully understand how to use your interfaces without ever looking at a line of your code.

Related Topic