Your Code is Not Self Documenting
There is this movement that people should try to write a self documenting code. Such code doesn’t require any comments, because it is obvious what it does. While that might be true, it’s not the whole truth.
Imagine the following code
def backup backup_database() backup_repositories() backup_emails() push_backups_to_s3() end
At a first glance, it is obvious what the code does. But what happens when you need to extend it? You actually didn’t remove the complexity itself by writing such code, you just moved it somewhere else.
Everyone who wants to work with the particular code still has to go to the definition of each method and check many, many things:
- does it check parameters?
- does it throw any exceptions?
- does the implementation look like I expected?
if there are tests available, it’s also a good idea to look at the tests and see how the method is supposed to be used.
Imagine working with a framework which didn’t have any documentation. Every time you would try to do something, you would have to look through the source code, understand it correctly and figure out how it should work.
But we prefer to just look at some guide or docs instead, don’t we? Then why don’t we write documentation for our own code?
Yes, writing a lot of documentation can actually start to hurt you. Not to mention that you’re going to have to maintain it, like you maintain the tests you write (oh yes, you should be writing tests).
You absolutely have to keep the documentation updated, because when you don’t, you can end up with stuff like
# this method doesn't throw any exceptions def foo(bar) raise KabOoOom unless bar.empty? # ... end
Being able to trust your documentation is very important, because if people don’t trust it, why have should they have it at all?
But I don’t have the time for this
You don’t have the time to write one sentence to each method you write? Do you really think that you’re that busy? How about the time you save other people while they’re reading through your code?
Keeping the documentation up to date also takes time, but is that even comparable to the time you spend on the code itself? Almost all programmers type fast, say 400+ characters per minute. So how long does it take to write one two lines of simple text explaining your code? 15 seconds maybe?
If you’re not able to explain what the code does in around two lines, you probably have a design problem. I’m not saying that you should never write more or less, it’s all about good judgment. But try to put yourself in the feet of the person reading it. Would he be able to use the code after reading your docs?