views:

568

answers:

19
  • When I'm writing it?
  • After I got a part done (Single class/function/if-elses)?
  • After I got the whole thing working?
+5  A: 

This is a matter of style. Personally, I like writing comments during the coding, not after. Because it I leave it to after, I usually get lazy and don't write them at all. That said, sometimes it's useful to go over a completed piece of code, figure out what isn't obvious from the code itself and document it. In particular, the parts where assumptions are made.

Eli Bendersky
+1. Write them during coding (but revisiting them afterwards to see if they are still correct is advisable too).
ChristopheD
+11  A: 

You should never "add" comments - they are not additions. Comments are part of the code - you use them when you need them. Asking when you should add them is like asking when you should add functions or classes. Though thinking about it, I remember doing a program advice slot at university I worked for where one of the students came in with about 1000 lines of Pascal, with no functions. When I queried why he hadn't used functions, his response was "I'll add them later, once I've got it working."

anon
That's something different. You won't have to refactor the whole code when adding comments, not so with things directly affecting the program..
ongoso
@ongoso Actually, writing comments may well cause you to refactor the program. If the comments are worth a damn, they will make you think more deeply about what you are doing.
anon
+1: I'm with @Neil on this: write comments when you write code. Write first-cut comments when you write first-cut code. Revise comments when you revise code. Dot the i's and cross the t's of your comments as you dot the i's and cross the t's of your code. Comments are in the source file text rather than external documentation for very good reasons, they are integral.
High Performance Mark
+9  A: 

This is subjective, but sometimes it's better to add them before the actual code, eg. when you implement an algorithm that has clearly defined steps. By that way it's harder to miss steps.

SurvivalMachine
Aaaah... yes...?
ongoso
I agree, I usually write comments immediately before I write the code; occasionally loop back and add some more while debugging.
EJB
A: 

Comments should reflect why you are doing the things the way you do, not what it does. Most of the time the one reading your code can read what it does.

You should explain the the things one cannot reduce from the code.

Ikke
Have you read my question? Seems like you didn't.
ongoso
I admit I didn't read your question. But it was meant as an addition to other answers anyway.
Ikke
A: 

I add comments while writing any code that is not easily understandable. I find that if I don't do it immediately then it gets forgotten. I (or more likely someone else) then spends more time figuring what I did than it would have taken to write the comment.

To be more precise, commenting immediately after the code is written is the best avenue to ensure comments actually get written.

Eddie
I don't talk about the advantages of (not) adding any comments. I'm talking about *when* to add them.
ongoso
I was giving a reason for why I comment <em>when</em> I do. An answer of "immediately" would be pointless without a reason. None the less, I could see how someone would look at the first sentence and not see that I mean comment immediately when the code is written.
Eddie
A: 

I tend to put basic comments as I'm going, just to remind myself what I was thinking at the time when I wrote it (i.e. why I wrote it that way). I do this especially if it's code that looks like it might be wrong but is actually right, or code that has an inherent race condition that I don't care about, or code that might not be optimal but is a quick way to get something working, so that even ten minutes later when I go back and look at it I can see that I've thought about the problem already and don't have to waste any brain cycles on it.

When the code is more complete, I'll often go back and review the comments I've written and then have a think about whether I still think the decisions made are reasonable, and whether things could be done better. I'll also often expand the basic comment into a longer comment that's more useful for other people when they come to maintain the code; I usually save comment expansion to the end because a lot of the time basic comments just get deleted during refactoring, so writing a long comment is a waste of time until you know you're going to keep it.

In a nutshell, write basic comments as you go along, and then improve them as your code becomes more stable.

Oh, and also, any time you review a bit of existing code and you're struck with a WTF?! moment but then realise the code is actually decent, put a comment in to save yourself and the next person time when they look at it in the future.

Greg Beech
+2  A: 

I would suggest writing comments whenever you edit any code, while you are editing it. According to Robert C. Martin in Clean Code, a disadvantage of comments is that the code can change without the comments being updated, making the comments not only useless, but dangerous. To reduce this problem, if you must use comments (because you are unable to express yourself in the code itself), make sure you update them every time you update the code.

Daniel
+1  A: 

A disadvantage of adding comments later is that a lot of times that will simply not be done, due to lazyness, other tasks, etc.

If you find you can always go back and add the appropriate comments without any problem, then by all means do so, but otherwise making a conscious effort to add them as you're coding or before you code a section may be a way to ensure that you don't leave the code uncommented.

JRL
A: 

Put a comment ANYWHERE the programmer reading your code, may generate a WTF moment.

If you find yourself commenting every line, perhaps you need to take a look at trying to improve your code with simpler, more elegant statements.

Dominic Bou-Samra
A: 

The question should be, when do I add code to my comments?

My practice is to write out the functionality of a module/object/function as a series of comments. Not comments like "add one to counter". Higher level comments like "sort list by account number". Detailed comments are pretty much redundant with the code. So I avoid those unless I'm writing a very tricky algorithm. Once I have the functionality "designed" in comments, I act like a human compiler and add in the code after each line of comments.

Give it a try and let us know how it works!

HugoFirsth
A: 

Personally, I tend to write comments to summarise code where necessary - often before I write the code, as well as to save WTFs. I treat them very exactly as notes - of things to do, things that I have done this way, or will do this way, and as such they are put in when and where I feel the need for them.

penguat
A: 

Before you forget what specification and design the code is required to implement. Before you forget that some unfortunate coder will have to read it later on. Before you forget that the unfortunate coder could well be you.

Sam
A: 

When you do something non-trivial, as you're writing it.

Alex
+20  A: 

The short answer

The short answer is anytime something is non-obvious relative to whose going to be reading it. If its code that is still in flux so you are the only consumer, just comments for you (hours and days). Ready to check in for others to try out - comments for you and your team (days and weeks, possibly months). Ready for wide release - comments for the immediate and future public (months and years). You have to think of comments as tools, not documentation.

The long answer:

  • When I'm writing it? - Yes
  • After I got a part done (Single class/function/if-elses)? - Yes
  • After I got the whole thing working? - Yes

When I'm writing it? - Yes

Drop comments anytime you hit a place where the code isn't immediately clear. For example, describe the class when the class name isn't clear or could be interpreted too widely. Another example is if I'm about to write a non-obvious code block, I'll first add a comment reminding me of what I want/need. Or if I just added some code and I immediately realized there was a gotcha in there, drop a comment to remind yourself. These comments are implementor comments, less to help future maintainers, but rather to help yourself in the coding process.

Drop FIXME - explanation and TODO explanations reminders as you go.

Code is still in flux, so I'm not yet documenting every and all method and parameter.

After I got a part done (Single class/function/if-elses)? - Yes

When I'm reasonably done with a method or class, now is the time to review it. Along with checking scopes of methods, ordering methods, and other code cleanup to improve understandability, now's the time to begin to standardize it against your team standards. Consider what comments are need based on the audience it will be released to (future you is part of the audience too!) Does the class have a header block? Are there non-obvious conditions under which this method should not be called? Does this parameter have any conditions on it, e.g. should not be null?

Check the FIXME and TODO items - still valid? Any you should address now before moving on?

These are still notes for you and your team, but the beginnings of standardized notes for future maintainers.

After I got the whole thing working? - Yes

Now is the time to review everything and finalize comments against your standards.

All FIXME and TODO items addressed (fixed or captured as known issue)?

These notes now are for future maintainers.

Now the dirty little secret

More is not always better. Like unit tests, you have to balance use of your tools weighing costs vs benefits. The fact is that a coder can only type so many physical lines per hour - what percent should be comments? A low percentage means I've got a lot of code, but its confusing and difficult to understand and use correctly. A high percentage means that, in an hour when someone changes a method signature or redefines an interface, all the time is spent fully commenting every parameters of those methods just got trashed.

Find the right percentage based on the stability of the code, how long it will live, and how widely it will be released. Not stable yet - minimal comments to help you and your team. Stable and ready for project - fully commented. Public release? - fully commented (check again!) with copyrights (if applicable). As you gain experience, adjust the percentage.

Bert F
Nice and intelligent answer, I'd just like to add that writing comments at all can be avoided. Better variable naming, function names and better design in general should eliminate the need for comments. (in a perfect world)
NomeN
@NomeN Wholeheartedly agree - if I had to choose, I would rather clear names (even if a little longer) and straightforward, understandable code. I really wish languages had more ways to capture things as both code and documentation, e.g. a way to annotate that a parameter may not be non-null. In an ideal world, this annotation would be used by a static analysis tool, it would generate assert code (optionally executed when a flag was turned on), *and* incorporated by the documentation generated into API documentation as part of the method signature.
Bert F
@Bert: That said, annotations still can't capture all features of code; things like whether the algorithm is O(1), O(n) or O(n²) really matter in practice, and they aren't “correctness” features so much as “quality” features. Comments are good because they're intended for consumption by another programmer (or yourself in 6 months :-)) and so they work at whatever level makes the most sense.
Donal Fellows
@Donal Sure - I'm not saying comments should go away. I'm saying it would be nice to codify some things we often end up writing comments about so that tools can assist us more to increase "correctness", "quality", and understanding.
Bert F
@Bert F: there are some programming languages that enforce ranges, which you can then document through your naming. For example Ada springs to mind.
NomeN
Contract4J - see listing 1 in this article - http://www.ibm.com/developerworks/java/library/j-aopwork17.html
Bert F
A: 

You gave a lot of cases in your question. I think it depends on what you're doing at the time.

If you're writing a function or a class, comments are a way to declare what's supposed to happen with the function. Things like input variables, output type, special behavior, exceptions, etc. IMHO that kind of comment should be written before the actual code is started, in your "code design" phase. Most languages have packages which process those kind of comments into documentation (javadoc, epydoc, POD, etc, so that stuff will be read by users.

If you're making a bit of code work, I think it's OK to wait until you've got it working to put in a comment triumphantly describing your working solution. That kind of comment is only going to get read by a code reviewer.

Then, as others have said, you want to avoid WTF moments, by yourself or others. I once got an attaboy for a comment I made once in an open-source project. The comment was "Yes, I really do want = and not == on that line."

Matthew Leingang
A: 

Hi A. when you decide an arbitrary decion that would be difficult to re-understand. B. Every thing that you feel that you should remember while writting the code C. in the beginning of a program explain the logic and use Advice - instead of commenting a lot use long names for functions and vars that realy explain what the function does or what the variable stands for.

ariel
A: 

Mostly at time when you write that code. You can go there after the function/block/whatever is done and organize your comments on fresh mind. Most of the stuff we write while coding are not meaningful later.

Ivan Petrushev
A: 

Early on in my career I added comments to nearly every line of code, as you may do perhaps in an ASM program. As time went by I ran into many of the problems mentioned here. It was a bear to maintain which resulted in not updating comments and then they become stale at best, usually moldy.

I feel that the # of comments should reflect how complex or non-obvious the code itself is. In a more challenging environment, such as ASM, you will probably need more comments to understand what is going on. In more modern languages like C# you shouldn't need a whole lot of comments in most cases.

Generally I use tools that evaluate the complexity of my methods in C#. Those that are high on the complexity scale first get refactored. Then when I'm satisfied with the complexity remaining and I still have some code that is not obvious, or even more important, seems obvious but does something different, then I tack a comment on it.

John
+1  A: 

You should try writing comments BEFORE you write any code. eg

public string getCurrentUserName() {
    //init user database repository


    //retrieve logged in user


    //return name if a user is logged in, otherwise return null

}

Writing comments before you code, helps you learn how to structure your code without actually coding it and realising that you should have done it another way. It's also a good way to quickly visualise a clean solution to a complex problem without getting bogged down in implementation. It's also good because if you get interrupted, when you come back to your work you can go straight back to it, as opposed to refigure out what you have done and what you need to do next.

Not suited to all situations, but often a good option!

Alistair