I was reading Scott Hanselman’s blog yesterday (computerzen.com) and read a good post about coding basics. I left a comment about the process of coding and making your code better. I thought that one thing in particular was worth writing about here on my site.
There has long been debate about the value of commenting your code. I grew up with code commenting and have continued to do so through my career. The main arguments against commenting code seem to be that a) the code itself is or should be self-documenting and b) comments are often wrong, so why bother.
My answer to these is:
a) I’ve read so much code in my life that is incomprehensible that I wished the person who wrote it had written a comment (or many) about what the code was trying to do – especially because it’s rare to find non-buggy code. Sooner or later, someone’s going to have to go back to that code and fix something.
b) If the comment is wrong, even that’s not so bad. Out of date comments are a place to start. For some reason, when you see a comment and try to evaluate the code, it’s not that hard to figure out that they’re out of sync. There’s clearly some mental process that gets invoked that helps you understand what the code is trying to do. Plus, if the comment is actually correct, you’ve just clued the person into what’s really going on (or is supposed to be going on).
Clearly, I’m in the “keep the comments” camp. One thing I started doing a while ago is functional design by comments. Before writing a function or object-oriented method, I write a comment for what the function will do. Then, I outline the code by writing comments. Writing code this way forces you to think about what you’re going to code and not just jump in. Once you do this, you start thinking about ways to structure the code most efficiently and maintainably. One more benefit: if your comment on the whole function is huge, chances are that you’ll need to break down the actual contents into multiple sub-functions, allowing you to refactor at the conceptual level sooner, rather than at the coding level later.
Try this simple method for writing code for a little while and you’ll probably get hooked on it too. If one of your colleagues comes over to your desk some day and complements you on a well designed and documented class or function you’ve written, or you simply find your own code easier to maintain, you’ll know you’ve earned your next donut.