Document your code and live a happier life

Programmers and documentation have a long history of hostilities.
I believe that (good) documentation is a vital part of any software that is made to live more than a few days, specially when there are other devs working on the same code base – or that may eventually come to work on it, like a future hire.

The kind of documentation that I defend and ask people to do is the one which agregates value to the understanding of some concept, or help to make clear some not-so-obvious variable, method or class name or piece of code. I know, I know, naming convention plays an huge and important role, but lets be realistic: there are times you run out of good names, or you are just not that inspired, or the code is simply too complex.

I am also aware that there are people which believe that “the tests are the documentation”, but I am yet to seeĀ  it to work in practice – it is not practical to require someone to read hundreds of tests just to grasp some concept or business rule that could have been expressed in a few lines of documentation.

Tell me, how do you learn a new framework or library? There is a high probability that at least a with instructions and sample code exist, but more often than not you will find some good API documentation, howtos and guides. So, if you expect to third party libraries to have documentation, why shouldn’t yours?

Good and concice documentation takes seconds to write most of the time, but can save hours (if not days) of code reading and debugging.

Let me show you two very simple examples. Take a look at the following code:

What does it do? The function name suggests that it returns the row of the resume thing, but what it returns? An object, or a number? Also, why is the body adding 16 to month?

This is how I’d improve it:

Another example:

You can see that the function expects three arguments, but what is the format of “key”? And “type”? And “today”, it expects a date object, a number, a formatted string?

Here’s how it could easily be improved:

Good and valuable documentation is easy to write, and can have a tremendous positive effect in code quality and delivery times.

Leave a Reply

Your email address will not be published. Required fields are marked *

7 - two =