Amos and I got in a heated discussion recently on whether we should write a single line comment to better explain some code. (The code in question was Amos’s very elegant solution to testing whether a job got sent to Resque.)
Amos doesn’t believe in writing comments much at all. He thinks that if you’re writing a comment, it means that you’re doing something wrong, and that you probably need to write the code more clearly.
I agree with that, to a point. First off, it’s not necessary to write perfect code. If you can change a class or method name to better describe what you’re doing (and more importantly, why you’re doing it) then you should definitely do so. But it’s not always worth refactoring until you get every “why” answered. More importantly, I don’t think it’s even possible to capture everything in the code that is worth capturing. For example, why did you choose this implementation, as opposed to another that might be more obvious or common?
After our argument, I came up with a good rule of thumb (or “pattern”):
Write comments for your (future) self.1
In other words, if your comment will help you to understand the code more quickly when you look at it in the future, then it’s a valid comment. It also means that you can assume that the reader has about as much general programming knowledge as you currently do. (Your future self will have more general knowledge, but possibly less specific knowledge of the lines of code in question. And because of this, your current solution might not make as much sense in the future. You might know of a better solution in the future, but you’ll have to know all the constraints that you had when you originally wrote the code.)
This is not to say that you should not write comments in clear English, that others can understand. The comment is written for a future maintainer. That may be you (which is why the rule works well), or it may be someone else. The rule is more about when to write a comment, and what level of competence you should assume of the reader.
Perhaps it should be “Write comments TO your (future) self”. ↩︎