views:

767

answers:

20

Yesterday I was going through some code of mine which made no sense to me at first (written less than a month ago). When I understood it, I quickly added comments to avoid the exercise. This made me think that, had I commented on the code as I wrote it, my comments might not have helped a later "me" decipher the code.

When in the code's life-time is it best to add comments? If the answer is that it depends, what does it depend on?

Note: I am asking for experience- or, better yet, literature-based answers, moreso than "thoughts on the subject." Also, please note that this question assumes that you do need to comment code (occasionally, sometimes, or always).

+20  A: 

You should always comment code explaining why a module does something, not what (that's what the code is for :)) Anything that is not clear as to why something is happening needs to be commented. Code should be written well enough to be understood on it own.

I am going to clarify my last comment a little bit. Sometimes I feel it is ok to comment what code is going to do (i know this contradicts my previous statement). There are things in code which some people won't be able to understand. It's not that the code is written poorly, it's that the concepts they use are advanced and people get confused. I am thinking of things like recursively creating trees, graphs etc. Things that may be clear to you, but could cause other people trouble. I think this goes on a case by case basis, and depends on the team you are working with.

You should always write comments BEFORE you write the code. You should always know exactly what something is going to do and why before you code it out.

Kevin
which is exactly why methods and variables should have informative and helpful names.
Stan R.
Comment Intention, Not Function - if you're explaining function in a comment, the libraries you're using aren't well-commented in intention.
DDaviesBrackett
Interesting... I mean the last paragraph, of course. Before you write the code. Hmmmm... I'll try that (I think I've tried that before but it's been a long life :)
Yar
I find it useful in planning things out. You write a comment and then realize that what you are thinking is totally off. It sure beats write 20 lines of code and then delete it.
Kevin
I sorta vaguely disagree with the last paragraph. The rest is so awesome, however, that it's an easy +1.
Beska
A nice way to reach it is first write the entire function in comments. Start with (typically) 3 or 4 lines of comment explaining the main structure. Then, refine by splitting up each line in slightly more detailed lines of comment. At some point, a line of comment can be trivially translated to a line of code. Don't delete all lines of comment from your 'tree', and you've got yourself a neatly commented function.
Martijn
CDD is now a new development methodology: Comment Driven Development
Even Mien
+1  A: 

I think the problem with comments is less about the "when" and more about the "how". If people commented code properly in the first place, then the "when" wouldn't matter - if anyone could come back to the code at any time and understand what it's supposed to be doing, then the comments are well done. This of course goes hand-in-hand with writing good, readable code.

There are lots of questions floating around stack overflow about how to write good comments, (for example http://stackoverflow.com/questions/779025/are-there-standard-formats-for-comments-within-code/779087#779087) but fundamentally it's going to differ between organizations and personal styles. The ultimate goal of comments is to assist in understanding the code.

As long as you write comments properly, when you write them should make no difference.

womp
+1 I like your answer, but I totally disagree. I'm going to try writing comments before coding now to see how that goes...
Yar
+5  A: 

I have had best results doing this directly or shortly after writing it. That is, not while coding (it tends to distract me), but at least before I commit a change or merge it back into the master branch.

If I don't do it directly, I tend to forget it or care less about it. That said, if I revisit code and notice it could use some comments, I add them anyway.

Update: others make good points about writing comments before starting, but my experience is that it leaves behind a trail of commented-out pseudocode (which is terribly distracting and pointless).

molf
+7  A: 

I avoid commenting code, preferring to write code clear enough to not need comments. But sometimes you have some "tribal knowledge" embedded in the code. In that case you need to explain why the code does what it does and not so much what the code does.

ReadySquid
Sometimes I will plan out what I want to write with comments, and then delete them after the code is written leaving only the comments that explain why.
Scott
Thanks. I know some people do not write comments. But those are the assumptions of the question...
Yar
Definitely! I can't believe I forgot to mention that. That's mostly how I use comments anyways, as a rough sketch of what I'm about to write. If I'm writing an algorithm with definable steps, I'll make a numbered list and write what each step will do. Of course that all gets deleted when I'm satisfied with the code.
ReadySquid
The problem with this is that sometimes it is painfully obvious *what* the code is doing...but there's no clue why the person is doing it. More than once I've seen some very bizarre looking code, that looked very buggy. I could figure out what it did, and it looked wrong...but it turned out that it was right...it's just that it was doing a very bizzare and incorrect looking thing on purpose because of some unseen requirements. Without comments, there's no way to know that kind of thing.
Beska
Comments are useless if noone will read them and if even getters have comments that means that comments are not very usefull in that project. The less comments the more they mean.
01
+5  A: 

My general rule is - code as transparently as possible (following the "self-documenting code" theme). When what you're doing is not self-explanatory, comment it. For instance, deallocating variables really doesn't need to be commented. Looping through an array to do work on it's members should - no matter how simple the loop is, its quicker and easier to understand a code comment than it is to traverse the loop and make sure that it's not doing anything unexpected.

As to WHEN, I prefer "before you write the code". You won't do it justice after the code is written. Write a comment that explains your intentions, then execute those intentions in code. Check the comment to make sure that it's still relevant, and you're GTG.

I highly recommend Code Complete as a very solid resource on when and how to comment code (among other best practices).

Aaron Alton
Nice, thanks for paragraph 2. I'll have to try this...
Yar
A: 

I think you need to comment your code anytime it's doing something that isn't completely obvious from the source code itself. Obviously this will depend on many factors, one of them being your audience.

When I write code that I know I'll be the only one working with, my comments tend to just list places where there's weird behavior or code I've taken from somewhere else. Most of the time, the code I wrote in the past makes perfect sense to me just by looking at the source.

That said, when I write a tutorial that I hope many people will read, I comment out each section of the code and explain what each line is doing that is outside basic programming structures. That way, when they're reading the code trying to figure out what's going on, the full English explanation is right above the line of code itself.

Ryan Smith
Hi Ryan, could you please check that you're answering the question I've asked? Thanks.
Yar
+1  A: 

I am going to sing the same song again: do give "Clean Code" (Robert C. Martin) a read. As I advocated in this post

There's an excellent couple of chapters on naming conventions, code readability, and also COMMENTS. Well supported advice on how and when to write comments in your code.

Peter Perháč
I didn't downvote you (nor upvote you, yet) but would you mind explaining a little bit why this is relevant (if it is)?
Yar
Clean Code has a chapter on when and how to write comments and chapters on how to write and name functions and variables so that you don't need to write comments
Logan5
exactly as Logan5 explained. There's an excellent couple of chapters chapter on naming conventions, code readability, and also COMMENTS. Well supported advice on how and when to write comments in your code.
Peter Perháč
+3  A: 

In principle, you should comment the code as you write it, but, as your own experience just demonstrated, you're often too close to the problem to write the best comments. In my experience, this is a strong argument for some form of code review, whether the continuous review of pair programming or something more formal, as appropriate -- "comment that more thoroughly in such-and-such a way" should be an expected outcome of review by other eyes.

Richard Dunlap
Nice, if you have the luxury of a code review.
Yar
+1  A: 

I usually write some quick comments on tricky areas as I'm going, and then when I finish a major chunk (a completed class, for instance), I go through and comment everything more fully, making sure that any comments I already made reflect the current reality. One of the worst scenarios is commenting something, then making a significant change, and not changing the comments to reflect that change. In many cases that is worse than not commenting because you may be directly giving false information to the reader of your code, and they'll often believe the comments over the code itself.

Gerald
+1 Interesting, thanks for that... it is a major pitfall.
Yar
I run into this especially when the comment says what other parts of code use the thing being commented. These comments can be helpful in giving an understanding of how the program fits together - but it is so easy for those other parts to get replaced or removed or simply just renamed leaving comments which point to them like this unchanged and misleading.
Anon
+8  A: 

When somebody reviews it for you, and they say "I don't understand this bit".

Scott Langham
Thanks. Funny, true, and you actually understood the question.
Yar
I sort of agree with this...it's true that it should be commented then. But really, it should have been commented before then. The risk with this approach is that you won't be able to comment it when someone else needs you to (because you're gone, dead, forgot what you were doing, whatever.)
Beska
I think Scott is assuming that you actually have a review process in place. Otherwise the wait might be 5 years...
Yar
+1  A: 

I really encourage you to read this book: Code Craft: The Practice of Writing Excellent Code

There's a whole chapter about this topic.

Here are some key concepts from that chapter:

  • Learn to write enough comments, and no more. Favor quality, not quantity.
  • Spend your time writing code that doesn't need to be propped up by tons of comments.
  • Good comments explain why not how.
  • When you find yourself writing dense comments to explain, step back. Is there a bigger problem to solve?
  • etc.
VVS
Could you share the name of the chapter, if you've got it?
Yar
It's Chapter 5: "A Passing Comment - How to Write Code Comments"
VVS
David, I'm not going to downvote you because I don't do that, but could you please consider if this answers the question I ask? Thanks.
Yar
Those key concepts I posted are not directly related to your question but the books chapter is. The book itself is the literature-based answers you're asking for. I really recommend you to inhale the concept of self documenting code.
VVS
+6  A: 

If you plan on commenting later, you probably won't comment at all.

Jon B
so before is good, then, Jon? Before what? That's the question...
Yar
I comment right after I finish writing a method. That way the comments are up to date and accurate. If I comment before, I always forget to change something in the comments.
Malfist
+1  A: 

I am going to agree with the guys above about commenting "BEFORE" you code. This will help you to remember the purpose of the function/method/block of code. It is easy to get side tracked when coding and forget your original intention. For example if you are writing a getFoo() function and can't remember what it should return, then you're retarded. However, if you are writing a function that performs several nasty calculations while iterating through multiple data sets then the comments might just help.

amischiefr
Interesting, though now I think I just may be retarded.
Yar
+1  A: 

I have heard of (but can't find) the "Necessity Principle" with respect to the field of Education. To put it plainly, students learn when and what they have a need to learn. There are analogies to TDD (only write code with a failing test to demonstrate its need) and Lean (Just In Time, in particular). I think what you demonstrated with yesterday's comment was the application of the Necessity Principle to commenting, and I think the way you went about it, and your schedule, was just fine.

At the time we write a method, we are conscious of what is important about it with respect to the immediate matters of interest; how it fits into the other code we're writing today, what false paths we took while writing it, why we wrote it in the first place. But we (often) don't know what we're going to want to know about it in the future - even as little as a month later. When we do need to know something more about it, and when it's painful to acquire that knowledge - that's a good time to record that new knowledge.

I'm not saying you shouldn't write comments before/during/immediately after writing code - that's a matter of personal and team standards and style. But when you are made aware of a deficiency in documentation - that's a great time to correct it.

Carl Manaster
+1 for that. This is too wishy-washy for my tastes, but most mature Zen answers are :)
Yar
+1  A: 

I dont always get to write this perfectly, but ideally, I prefer to

  • Stub out code and add comments as to what methods / classes should do
  • Write tests to cover them (TDD)
  • Go back to the stubs and fill the code in to pass the tests, the comments will help remind you what you need to do

I've found that this flows quite nicely for myself. I also didn't link to any "literature" on the subject because I think any literature on commenting is probably going to be silly, or what just worked for someone else. It may or may not work for you.

Edit: I've found that when I write very verbose comments, it really helps me arrange my thoughts quickly and concisely and will even allow me to refactor better (later down the road). I've also never had to stare at my code to figure out what it did later since the comments are there.

Also, if you comment later, you may misunderstand what your code does later and miscomment it.

Allen
Nice. Thanks for taking the time to read and respond to the question (and not just debate "are comments good?" for the 100x time)
Yar
+2  A: 

When it's fresh in your mind. You're unlikely to understand it any better than just after you wrote it.

Alternately, when you go back to older code, and have trouble understanding it, comment to write down what was difficult to figure out. Don't count on remembering it for next time; it doesn't work well for me.

That being said, document why, not how. If you have to document how, you're either doing some tricky stuff (in which case you need to document why you are) or you need to learn to write more readable code.

David Thornley
+1 Thanks for the first two paragraphs.
Yar
+1  A: 

I add comments after the code is ready and all the tests pass, but before submitting the code. I don't add the comments before coding, just because I usually refactor the code a number of times in the process of writing, and my memory is good enough to remember what's code doing when I'm working on it. So, documenting the code before the change is ready is wasteful. Also, it can be seen as kind of premature optimization.

Then, after the code is submitted I add comments only if someone can't figure out what's going on and is asking me. (Someone - including myself).

Igor Krivokon
+1 Thanks for that answer, fits the question like a glove.
Yar
+2  A: 

I tend to write class comments before I write the code, and method comments right after I determine the parameters and write the method skeleton. These get updated as I evolve the design. I try hard to pick very clear variable names and simplify the code to reduce the number of statement level comments needed. I usually write statement level comments right after I code each method body, but sometimes I need to work out an algorithm in comments first.

The key thing is to comment when things are fresh in your mind. By spending time explaining your code to others, you'll also tend to find more bugs and areas where the code needs refactoring.

Jim Ferrans
Thanks Jim, especially for reading and responding to the question.
Yar
+1  A: 

This made me think that, had I commented on the code as I wrote it, my comments might not have helped a later "me" decipher the code.

On the other hand, they might have helped.

Comments that were written in the past are often more useful now than comments which haven't been written yet.

If you ever deliberately delay writing comments then you might fall prey to "le mieux est l'ennemi du bien".

ChrisW
Yes. Just for reading the question, +1. I think that Voltaire quote is called "a bird in hand is worth a hundred flying," more or less. Which is probably the same expression in French, now that I think about it. Better some mediocre comments now than some perfect comments later.
Yar
A: 

It has been my experience that it is better to always comment code, even when the method and variable names are self-explanatory. It is much easier to come back to a piece of code 2 years later and understand it when there are comments. Comments make code that much more maintainable.

Mr. Will
I don't know if it answers the question (wrong "when") but I think you're probably right. I think some comments always help.
Yar