I have a bad habit of putting off documenting my code as long as possible; it’s often my last task before I submit a pull request. And every time I’m slogging through hundreds or thousands of lines of code writing documentation, I think ‘Next time, I’m going to do this as I go along.’ And the next time I write a new feature, I’ll probably leave the documentation until the end again.
As bad as this is, though, I’ve realized there are a few advantages to waiting until your code is finished before writing the documentation:
- Minimize wasted effort: In an ideal world, your API and requirements wouldn’t change after you’ve started coding. But how often does that happen? If you need to change your code and you’ve already documented it, now you have to waste time updating your documentation.
- Forced self-review: Have you ever written a section of code, then looked at it later and realized you could have done it better? While going back through your code to document it, you are forced to reevaluate everything you’ve done; the extra time between coding and documenting can sometimes give you the perspective you need to refactor it.
- Catch dead code: Nothing makes me want to delete unnecessary code more than having to document it. Before I document a method, I’ll probably check to make sure it’s actually still being used.
- Consistency: I find I used more consistent terminology in my documentation when I’m doing it all at once. I get in a zone, find a language I think works, and stick with it the whole way through.
Of course, there are some reasons nobody actually encourages this behavior:
- It’s awful: If you don’t enjoy documentation (and I definitely do not), it is really painful to write it all at once. Writing the documentation every time you write a method is annoying; writing documentation for dozens of methods is brutal.
- Faded memory: By the time you finally write the documentation, you may have forgotten what the code does or why you made certain decisions. On the flip side, this is a good indication that you should refactor your code anyway.
- Eh, forget it: When faced with this monumental task, it will be very tempting to just skip the documentation, or put it on your TODO list for later. Sometimes you may be able to get away with this, but you really never should.
So I guess I’m not exactly recommending that you wait until the last minute to write your documentation. I’m just saying that there are some upsides to it. Or maybe I’m really just trying to justify my own behavior…
Reference: A case for putting off documentation until the end from our JCG partner Jerry Orr at the Jerry on Java blog.