views:

2233

answers:

42

I usually comment "ifs" and write in "human language" what it means, like "checks if it's A or B".

I find it's better for junior programmers that read the code to read what it means first and then analyse the statement (also for me when I'm checking old code)

What do you do? What about other scenarios? Pros? Cons?

+4  A: 

Aside from descriptions of methods and properties and such, I generally don't comment my code, unless there is a bit that is particularly hard to understand. My personal goal is to write code that I can come back to in a year and make sense of in about 5 minutes, and I usually achieve that. The best code is easy enough to understand that it doesn't need reams of comments.

DannySmurf
A: 

I try to remove move the comments to separate functions when it seems the function is getting big.

To look big sooner I use a big font size like 14 or 15.

Artur Carvalho
+1  A: 

I comment as a service to others, and only when the code is "done". When working on my own projects I rarely bother since I'd rather be adding features and fixing bugs than writing something I'll probably never read.

Interestingly, when reading other people's code, I very often delete or ignore the comments and look directly at the code. I find that is many cases it can be clearer to read than the corresponding comments.

Kyle Cronin
+3  A: 

I don't comment the obvious stuff (i.e. "Set i to 2" or "check if a is greater than 5"), but sometimes just a little information about what the code is used for, i.e. "build the outer table" or some oddities like "MyClass.Count is actually Count-1". And of course, Workaround for bugs, i.e. "Workaround for KB123456 - url to some site that explains the bug...."

So basically: I almost never comment the "What" but sometimes the "Why".

Michael Stum
+39  A: 

Comments should not be "how" something is done, but rather "why" it's done (except in the VERY rare condition where the how is not obvious from reading the code, and I mean that is SUPER RARE).

Brad Wilson
+1 because how comments are usually worthless. The why is much more interesting.
Tim
A: 

I document what the function does, its parameters and what it returns and why. Inside the functions, I rarely comment anything. I find that if the variable names are chosen well, then they're all the commenting that are truly needed.

I write mainly C# code nowadays, but I find this system works for pretty much any object-oriented language because functions in well-factored OO generally don't go longer than fifty lines. If they do, I might sprinkle some comments in to document subsections of the process, but at that point I generally just break the single function into subfunctions.

Lee
+3  A: 

The problem with comments interspersed with code is that when the code changes (the code will change) the comments very often do not, or at least not consistently. This leads to even more confusing, unmaintainable code, because after several changes the comments and code don't say nearly the same thing.

Instead, I prefer to have comments for each module (class, function, whatever). This comment section should explain in plain English what function the module is intended for.

If I think a section of code is tricky enough to warrant a comment, then I refactor it out into its own function so the function name and related comments can explain what it is supposed to do.

Bill the Lizard
+1  A: 

I try to comment only on things that are necessary. Like what is the purpose of this class, what does this method do (if not obvious), which values can the parameters be etc. I try to avoid comments that describe what the code does. Instead, I try to make the code self-descriptive. Extract smaller methods from big chunks of code etc. Of course, this is not always possible and may sometimes even make it worse. You have to find the balance where your combination of code and comments is the most readable. The worst thing you can do is add comments to obvious methods like getters and setters when they don't do more than what they should - get or set the named field. One thing that is really dangerous about comments is that they may get outdated when the implementation changes and the comments are forgotten. So you should try to focus on the interesting stuff, because that's what users of your code or yourself will see and have to trust, if they don't have the source code ;)

Martin Klinke
+18  A: 

I usually comment "ifs" and write in "human language" what it means, like "checks if it's A or B".

If you find yourself doing this, it may be better to refactor so that the complex boolean logic is extracted to another method, or at least introduce a variable with a name that makes it clear what the logic means.

The problem with comments is that they (sometimes) violate the DRY (Don't Repeat Yourself) guideline. When you duplicate the logic by adding it to documentation, even comments right next to the code, you run the risk of having things fall out of date. Soon the comments may become incomplete or inaccurate.

That said, I don't mind looking at comments, even if they are a little out of date. I have run into code that looks like:

// collect data
Data data = collectData();
// analyze data
Report report = analyze(data);
// print report
report.print();

Those types of comments are absolutely worthless to everybody and I will usually delete them on sight.

Outlaw Programmer
I will delete whole the code and write : analyze(collectdata()).print();
Behrooz
+2  A: 

I realize it's kind of cliche, but the code should document itself. I tend to err on the side of declaring more variables for the sake of clarity (on the assumption that the compiler can/will optimize the unnecessary ones away). Keep the functions short and variables and functions well named. I try to do that and then only comment the tricky stuff.

Be aware, though, that shorter functions make it harder to see how the code, as a whole, works together. Keep this in mind when documenting functions (as opposed to individual lines of code). At the function or even unit level, you should be documenting how the functions interact with each other.

Johnny Edge
+1  A: 

I believe at the beginning of routines/methods/modules that you document the reason/intent of the entire piece of code. It's good to include comments on changes (who, when, why/what). In the code itself things that may not be clear or assumptions that are made should be commented.

Don't do comparisons with hard coded numbers use constants with meaningful names.

I have had to maintain code that was refactored down to one and two line methods with seemingly meaningful names, but the reality was there should have been comments to give the bigger picture of what was going on and how the methods related to other things that were going on.

bruceatk
+22  A: 

I have learned the hard way to code for the lowest common denominator. That encompasses a lot of behaviors.

  1. comment blocks of code, not necessarily every line. Explain why the following block (or stanza) of code is written the way it is. Include a date and your initials in the comment, so you know when the comment was put in and who wrote the comment. Try to avoid commentary like "this is stupid" or "I am so darn brilliant" as it really doesn't help, and may be proven wrong in the future. If you use any fancy tricks or do anything that isn't obvious from a quick glance, explain what and why.

  2. use human-readable variable names. that means avoid single-letter variables like the plague. it's much easier to guess what a loop does if the index variable is called rowIndex than i. Almost every civilized language has a compiler or interpreter that will scrub out variable names before putting your work into machine code, so using cryptic variable names does no one any favors.

  3. remember that compilers are smart. Very smart. Every modern compiler knows how to optimize loops and other basic things. Writing a complete while-loop on one line may look fancy to you, but it compiles the same and will trip up other people looking at your code (and even yourself if you come back to the code in a few weeks). Avoid fancy language tricks if they make the code less readable.

  4. adopt a style and stick with it. Always do ifs, loops, etc in the same format (and same indentation). You will be able to spot various features of your code more easily because the same features will look the same. If you make a mistake, it will stand out a little more.

Doing these things make the code more readable for everyone. Adopting good coding habits reduces dependence on comments, too, so it's a double-win.

Magus
This was very useful! I often write multiple function calls on a single line if I think they are part of the same "sentence", like. if(myHeight > yourHeigh) {me.hits(you); you.cry(); totalPain++; break; but after reading your post I think I will do less of that. It isn't as cool as I thought it was.
Ziggy
A: 

Like @Brad-Wilson said Why not How. But I do also use TODO's in my code as well, but for production I try to limit those.

Tom Alderman
+5  A: 

If a section of code needs comments. It probably needs refactoring.

e.g.

 void MyMethod()
 {
    //set the UI
    myTextbox.text = "Foo";
    myOthertextbox.text = "Bar";     

    foreach (n in thing)
      //something other stuff

 }

should probably be refactored to extact the UI stuff.

 void MyMethod()
 {
    SetUI();
    foreach (n in thing)
      //something other stuff

 }

 void SetUI()
 {
   myTextbox.text = "Foo";
   myOthertextbox.text = "Bar";     
 }
John Nolan
I'd change your sentence to say "If a section of code needs multiple comments, it probably needs refactoring." (a useful statement that I could generally agree with) if I were more sure that that was the meaning you actually intended.
Tchalvak
A: 

I used to write quite a lot of comments, and whenever I saw code without comments it just looked strange (I think I was used to seeing lots of green bits). Even when I stopped trusting comments and always skipped reading them, code would look strange without blocks of green text mixed in with the code.

These days, I almost never write any comments (the same goes for everyone on my team). The last few times I have wrote comments have all been warnings for the next person to see that code. E.g. "OPTIMIZED: Don't refactor this without running a profiler" or "WORKAROUND: Because of a bug in XYZ library we need to do ABC here"

If I come across comments that explain 'how' something works, I usually refactor the code so the comment becomes redundant then delete the comment.

Wilka
A: 

Turn to chapter 32 "Self-Documenting Code" of your copy of Code Complete.

David
+24  A: 

Jeff has an awesome post about the subject. Links in the post and some of the blog reactions are also worth reading.

Serhat Özgel
So another vote for "tell why" and "refactor down to simplicity", then, from the article.
Tchalvak
+19  A: 

There's a tragic flaw with the "self-documenting code" theory. Yes, reading the code will tell you exactly what it's doing. However, the code is incapable of telling you what it's supposed to be doing.

I think it's safe to say that all bugs are caused when code is not doing what it's supposed to be doing :). So if we add some key comments to provide maintainers with enough information to know what a piece of code is supposed to be doing, then we have given them the ability to fix a whole lot of bugs.

That leaves us with the question of how many comments to put in. If you put in too many comments, things become tedious to maintain and the comments will inevitably be out of date with the code. If you put in too few, then they're not particularly useful.

I've found regular comments to be most useful in the following places:

1) A brief description at the top of a .h or .cpp file for a class explaining the purpose of the class

2) A comment block before the implementation of a non-trivial function explaining the purpose of it and detailing its expected inputs, potential outputs, and any oddities to expect when calling the function.

Other than that, I tend to comment anything that might appear confusing or odd to someone. For example: "This array is 1 based instead of 0 based because of blah blah".

17 of 26
Insightful that no code with a bug (and what code doesn't have 'em) can truly be considered self-documenting. This is a powerful argument for why comments are a -necessity-.
Tchalvak
+1  A: 

I usually just comment in two cases.

  1. When describing the functionality of a method or class in an API that is meant to be used by others.
  2. When a block of code is doing something that isn't immediately obvious.

Of course I always try to give my variables and functions meaningful names, and minimize the need for comments that way.

Tebari
A: 
paperhorse
+2  A: 

The code itself should be able to explain how it works without any comments. The comments that accompany code should explain why it works.

You should be able to follow through the code of a function without comments and figure out what it's doing, but without the comments you'll never be able to understand why it does what it does. Well written comments explain how the function relates back to the big picture as well as for some of the day-to-day coding decisions that were made - the reason for wrapping a block of code in a conditional statement, or using a try {} catch {} for a seemingly innocuous looking set of statements.

Explanatory comments and the use of well named variables/methods/classes go hand-in-hand. You won't fully appreciate that until you get dumped on a legacy system that no current member of staff has worked on and that has zero documentation.

iAn
+3  A: 

Try not to comment the code. Document the API, but strive to write code that does not need to be commented, and is instead understandable from how variables, functions are named, etc. There are already several good answers to this here. Of course, when you're doing something esoteric or even kinky, and sometimes you have to, you should put a comment in the code.

But here's some additional stuff on how not to comment.

  • Do not put any creation/modification date in any of your comments. Version information in the header is OK, but not required, and probably not the best idea. Your VCS should take care of this. If you don't use a VCS on code that needs commenting, you're doing it wrong. Learn to use one (I recommend git or Mercurial) until it becomes your second nature.

  • FIXMEs and evenmoreso TODOs don't really belong in the code, and also not in the comments. The bugtracker is the right place for this. Or at least a toplevel TODO-file.

  • Keep your prosaic skills to yourself. Everybody knows you're a touch-typist who can write three pages in the same amount of minutes; but when I read code, I read code and prefer no comments to disrupt my thinking.

  • Do not try to explain the architecture of the system inside the comments. Even the API documentation is not always the best place for this. If the whole thig is really that complicated, use an external, properly formatted document that is easier to read, preferably in either pdf or html format.

Just remember: source files are what the code does. They are neither how it does it, nor are they why it does it. The how might go into the API documentation (which I do not consider "commenting" in the strict sense) and the why in the program's documentation. Do not confuse documentation with comments. Your management will thank you for this.

(If you were thinking about about literal programming, that's a whole other issue, and I do not have the sufficient experience to give you any advice here.)

Aleksandar Dimitrov
+3  A: 

In my current job I do comments that I have not done before - we are converting VB6 to VB .NET, and the other two programmers in the company have little or no experience with a true OO language. I do a lot of comments as an in-place tutorial type thing. Yes, that info could be in an outer document, or even in a book or on-line tutorial, but SO MUCH information exists! I give it in small relevant doses.

CindyH
A: 

There seems to be a lot of differing options on this subject, so I'm going to toss my own in the mix.

Generally the way I comment code is based upon a couple of things; namely, how I was told to write code a previous jobs, ensuring that I can come back couple weeks later and figure out what something means, and making things as easy as possible while I am actively coding.

In regards to how I write code at previous jobs, we tended to have a lot of inexperienced developers so one of the standing instructions was that the comments should reflect the psudo code for the function. So if you had something along the lines of the following,

Function getEmployeeIds
Input - departmentId (Integer)
Output - employeeIds (List of Integers)

 1. Open connection to database
 2. Query database for results
 3. Move results to a list
 4. Close the connection and release resources
 5. Return results

Then your code was expected to have comments that reflected those five steps also in the code. For the most part the comments reflected what the code was doing and there weren't any major issues with comments not being "on topic" for the function. Granted this is a bit verbose and you spend a bit of time documenting, but there was also no confusion about what the code was intended to be doing.

In regards to being able to come back a couple weeks later and figure out what I was doing in the code, recently I encountered some code similar to this:

Results.Append(IIf(oraData.GetInt32(1) = 0, 0, (oraData.GetInt32(1) / 60).ToString("0.###")).ToString() & ", ");

Looking at it, it may take a second to realize that it is converting from hours to minutes and someone that is unfamiliar with what is in the database might not know that the field is storing data as minutes. So a simple one line comment is helpful here to let the next person to see the code know what is going on.

Finally, making things easy while I'm working. For this most part I work with .NET languages and just about everything gets XML comments for the simple reason that they get picked up by Intellisense. The time it takes me to write the comments tends to be offset by the time saved by being able to use Intellisense if I forget something about the code I'm referencing. Likewise, having header documentation is also useful if I'm looking for something but not sure where it is. Having a general overview of what code is in a file saves time. If the names of previous developers is there then all the better as you can sometimes get in touch with them to ask how something works if they didn't document it well enough.

Rob
+1  A: 

Ideally, code should be "self-documenting", but please ignore those who say "if the code isn't self-documenting, you've written it badly". In the real world, this just isn't always possible, depending on the complexity of the code.

Obviously this doesn't mean that you should put comments everywhere, or have things like

option = option->next;  // get the next option
i++; // increment i

but if a piece of code is sufficiently complex, having comments right there that describe what it's supposed to be doing is far more valuable than having to go to some hopefully-up-to-date design document somewhere else.

Graeme Perrow
A: 

"I can't see the code for all the comments", is a statement or similar statement I've heard many times in my career. It is a warning that too many comments take too long to read and slows productivity.

So, in general I restrict my commenting to summaries. That is I'll give a summary of a class and its intent. I'll provide a one sentence summary for each method/property and I'll explain with more details a complex area of code. I rarely use in-line comments because it distracts from the flow and readability of the program logic.

Coder Blues
A: 

No, I don't comment.

Edit: Down votes for the only honest answer in the thread, huh?

Kevin
No, downvoted because you didn't say why.
Graeme Perrow
I don't think the other answers are dishonest.
Mike Dunlavey
A: 

As long as they warm the readers heart, i will.

//This function does stuff too complicated for you to understand, <3.
DylanJ
A: 

The longer I program (yikes, I've just entered my fourth decade), the fewer comments I write. I'm constantly refactoring my code to make it more self-explanatory, because that's flat-out easier and safer than writing comments to explain it.

I therefore find that when I go back and read old code, the comments I have written are nearly always worth reading.

The one place where I write comments even when the code is self-explanatory is in the method documentation, so that IntelliSense has something to display. Even though those comments may not be useful 100% of the time, it's just annoying if I mouse over a method call and nothing pops up.

Robert Rossney
A: 

I use comments to psuedo code a function out then remove the comment when the code is written. Unless it's quicker to read the comment to see what the code does, than work it out from the code. Then I leave the comment in.

Matt Lacey
A: 

Comment: whoever came up with the idea of measuring code as "X% comments" should die in a fire.

Coderer
+2  A: 

I find it's better for junior programmers...

If you're seriously questioning the value of writing comments, then I'd have to include you in the group of "junior programmers," too.

Comments are absolutely crucial.

Andy Lester
Good "why-comments" are good. "How-this-is-done"-comments almost always duplicate information that should already be *the code*, which is just bad (i.e. you need to change two things if updating the code and you have two pieces of identical information to follow).
Arve Systad
A: 

Complex code must be commented. Do you really believe that all code you write is intuitively obvious to all who read it?

No. Thought not. Comment your code.

bog
C'mon -- if it was hard to write, it should be hard to read. Why do you think they call it "code"? :-)
Adam Liss
+1  A: 

An old adage a mentor once shared with me, though I don't know the original source:

Good programmers comment their code.

Great programmers tell you why a particular implementation was chosen.

Master programmers tell you why other implementations were not chosen.

Or words to that effect...

Patrick Cuff
+1  A: 

Yes. I comment extensively. I do amusing things at a level where OO is uncommon, an operating system is a dream, and libraries are a myth.

So as I write drivers for an embedded system, I have to comment to make the groady, obscure code readable for my puny mind to read the next week. It also helps since there's large chunks of code I didn't write & don't have documentation for, and therefore I get to write in comments how to talk to that code where I do interface to it.

So, while the rest of you gurus may be so brilliant you can read uncommented C# - I'm not smart enough to read my uncommented C code. so I comment, and my code works pretty good. :-)

Paul Nathan
A: 

I no longer comment my code. I doxygenate it.

Marcin
A: 

I acutally find comments come before the code. I pseudo code with them, then fill in the code.

I've almost never found there to be too many comments in code I'm reading. The problem I see with commenting after I code is that when time is short (and it always is) that's the first step to get dropped. It adds to the work load because a bug later is hard to understand.. Not sure who said the comments are what's supposed to happen and the code is what does happen, but I really liked that thought. It shudders the self documenting code a bit. Not that I don't love to see well thought out variable/function names.

Refactoring code to avoid comments is not practical in all cases. There are times when it can be done but if you go around making two line functions to save on a comment.. Well blek.

baash05
pseudocode, not sudo code
wnoise
+1  A: 

One thing that should be more clearly highlighted in this discussion is the distinction between code comments and API documentation.

Since modern documentation generators work by parsing comments in the code (for example, C#'s XML-formatted documentation comments), some developers might mentally conflate comments and documentation. The general attitude against commenting code shown in this thread and elsewhere may cause those developers to not document their APIs.

While I agree that it's best to make the code clear rather than commented, I also believe it is important to document your interfaces. The documentation should not be too verbose either. It should only contain the information that would be valuable to the person using the interface. It should not contain any unnecessary implementation details. But the information that is present should be complete, so that the user does not have to ever look at your source code to use your module. The documentation that appears in the tool-tips of your IDE, or the longer document that appears elsewhere, should be all that is necessary.

This approach encourages encapsulation and, therefore, good programming practices.

/// <summary>
/// Gets the name of a seventeenth century philosopher. The name is 
/// chosen randomly among those that are stored in the database, 
/// whose primary cultural contribution was published between 1601 
/// and 1700. Names may be repeated on multiple calls. The 
/// ConnectionString property must be set before calling this method.
/// </summary>
/// <exception cref="InvalidOperationException">The ConnectionString 
/// property was not set.</exception>
/// <exception cref="SqlException">A problem occured with the database
/// connection.</exception>
public string GetRandomSeventeenthCenturyPhilosopherName()
{
...
Jeffrey L Whitledge
Thats one awfully fancy method, not sure I need it :)
leppie
Wait, wouldn't that be obvious to anyone who wants to spend the time to read the code? Just kidding, +1, these are the kinds of comments that are needed. Preconditions, expectations, etc. etc. Very nice.
Yar
A: 

I will frequently date-stamp my comments and describe WHY I am doing something, rather than how (after all, the how is in the code).

If I'm making a change, especially if it's user-driven, I will not delete the old code, but comment it out with the reason why it has been removed. It's like an "in place" versioning system except it allows me to read the history whenever I'm modifying the code.

-R

Huntrods
A: 

It goes back a couple decades, but there was something called "documenting the code with pseudo-code", and I developed a method. I said you should be able to take the code, strip out everything but the comments, and what remains should be that documentation. That's what I still try to do, even though the stripping-out part never happens.

Mike Dunlavey
+1  A: 

I try not to comment the obvious things, however the modern techniques of documenting the code often force to break this "rule". Consider the following code:

/**
 * Returns the user name.
 *
 * @return String The username.
 */
public function getUsername()
{
    return $this->_username;
} // end getUserName();

Do we need this "phpdoc" (or "otherlanguagedoc") longer that the function itself to know what it is supposed to do? No - the code itself is clear enough and obvious, but unless we add the comment, there will be problems with the documentation generators and IDEs.

Generally, I think that the answer to the question "what do we comment" depend on the code we are going to write. When making a website application, I unsually don't put any for the standard parts of the CRUD-s, because almost all of them follow the same schema: check the permissions, parse the input, optionally get the item, do the something with the database, redirect the user somewhere". Such code is easily readable even after two or more years.

On the other hands, we have a specialized code that solves a particular technical problem, for example a kind of parser. Here, the complexity is greater: we use some data structures, the algorithm may move the data between them to perform a certain task etc. If I see that the algorithm does not follow any popular schema, I describe the used data structures, its purpose and what operations are performed on them in order to complete the task. I also try to explain, why the specified solution was chosen. Here, I find the "somelanguagedoc" comment syntax useful - internal and system functions that are not exposed publicly, but also should be briefly described, especially in complex code just to know, what they are actually doing, why and what their arguments mean. The alternative is to find all the occurences of them and guessing.

However, I must also point that sometimes it is very hard to predict, what is worth commenting. A couple of months ago I returned to a piece of code in one of my projects to add some extra functionality. Suddenly I noticed a quite important condition and had no idea, why I used it. I think it must have been something obvious while writing this part, but even the investigation didn't help :).

The last comment practice I use is marking the end of the function, class and interface with its name:

void somefunction()
{
   ....
} // end somefunction();

It helps me navigating.

Zyx
+1  A: 

I have consolidated my commenting style on javadoc eons ago. Usually I comment only why something is done - rarely, if it is a complicated manner or an algorithm I also comment how it is done. Sometimes I comment in a little helper comment as I call them (though this happens rarely, as I tend to avoid doing code like that these days). For example if you have severe branching in code and you end up with code that ends up closing like this:

......... }
...... }
... }


if the code is somewhat long and doesn't fit a "page" I comment the closing braces to denote what is it closing on, just as a quick visual aid, for example:

......... }
...... } // end vertex loop
... }

or something like that, because usually you know which loop encloses which, you only need a quick visual aid to know where what ends - more verbosity added when needed. Though as I've said I tend to avoid spaghetti code that produces stuff like this, but sometimes it is unavoidable.

Keyframe