Why not to comment code
Update, Aug 18, 2009: I’m amazed at how much attention this post has received. More than 200 comments on Reddit.
I was just listening to the Why comments are evil episode of Deep Fried Bytes. The views put forward by the guest, Corey Haines, deeply resonate with me because I believe they’re what every developer should strive for. I’m not advocating that code should be entirely free of comments, but rather that most comments do more harm than good.
Below I’ve listed the main points of view.
- It’s important to differentiate between code comments and API documentation. For API documentation, don’t auto-generate. Especially don’t go with tools like GhostDoc. Take the time to document properly. Otherwise, you’re more likely to confuse the developer trying to make sense of your code.
- Stop focusing on having the computer understand you and start focusing on the person that comes after you, e.g., while there’s some overhead to method calls, unless the profiler tells you otherwise, don’t hesitate to break down a method into as many smaller methods as it takes to make it more approachable.
- Every time you’re tempted to comment, take the time to think if you can make the code tell its own story, e.g., instead of some branching condition, extract the condition into a method to emphasize the story of why over how.
- Developers comment to explain a confusing part of their code rather than take the time to refactor it by extracting a method or naming a variable properly. Inevitably the code gets modified and the comment rots.
- Parts of a method may be complicated so a comment is added. Saying part of a method is complicated is in itself a sign that it’s doing too much.
- The prevailing culture among developers is to focus on what it takes to get code working. It’s a battle of short-term vs. long-term maintainability and short-term almost always comes out as the winner. Writing code, ask yourself if you’re able to immediately understand the code a month from now.
The opinions put forward in the episode aren’t new. Still, I find them well worth iterating because as developers we tend to not pay enough attention to them. We tend to focus too little on good software craftsmanship.