views:

1136

answers:

18

How to keep the source code well documented/commented? Is there a tool to generate a skeleton for comments on the Unix platform for C++?

In general, how many lines of comments is recommended for a file with around 100 lines of code?

+5  A: 

I think this question has a lot of good relevant answers for a similar question: Self-documenting code

As for tools for creating comments, it depends on the editor you're using and the platform. Visual studio automatically creates space for comments, at least it does for C# sometimes. There are also tools that use comments to generate documentation. As for lines counts, I think that's irrelevant. Be as concise and clear as possible.

apphacker
+4  A: 

I think a good guideline is to comment every class and method with a general description of what each is for, especially if you are using an HTML documentation generation tool. Other than that, I try to keep comments to a minimum - only comment code that could potentially be confusing, or require interpretation of intent. Try to write your code in a way that doesn't require comments.

I don't think there is really a metric that you can apply to comments/lines of code, it just depends on the code.

Andy White
I disagree. Anything that crosses your mind while you're coding needs to be documented. The reader needs to know your mindset to understand your intent. IMO, you should have at _least_ 5 lines of comments per line of code--50% of which should be song lyrics you have stuck in your head.
Calvin
Yes, this is a valid approach. Song lyrics should be commented in source code as often as possible. Cursing is also good. :)
Andy White
-1. Sorry but source is *not* self-documenting. It tells you *what* is being done, but without comments, you have no idea 1) *why* it is being done, and 2) if what the code does is what the coder intended. Not commenting makes maintenance a hell.
DevSolar
I sort of disagree. Having too many comments can lead to even more confusion that not having any. What do you do if the code does not agree with the copious amounts of comments? Do you change the code, or the comment?
Andy White
Calvin
@ Andy, at least you know you have a problem in that piece of code, which is more than could be said without the comments...
DevSolar
+42  A: 

Generally, it's best to let the code itself explain what it does, whereas the comments are there to describe why it's like that. There is no number to stick to. If your 100 lines speak for themself, don't comment at all or just provide a summary at the beginning. If there is some knowledge involved that's beyond what the code does, explain it in a comment.

If you're code is too complicated to explain itself, then that may be a reason to refactor.

This way, when you change the implementation you don't need to change the comments as well, as your comments do not duplicate the code. Since the reasons for the design seldomly change it's safe to document them in comments for clarity.

Michael Barth
I agree, nice one.
Chuck Conway
+14  A: 

Personally I think skeleton comments are a horrible, horrible idea. I understand that sometimes it's nice to save couple of keystrokes and perhaps get argument signatures in comment... but resulting n+1 empty useless comments (when editor has added boilerplates and coder has left them as is) are just more irritating.

I do think comments are needed, at any rate -- if only code one writes is too trivial to ned explanation, chances are code in question is useless (i.e. could have been automated and needn't be hand-written). I tend to comment my code reasonably well because I have learnt that usually I need it myself first. That others can use them is just an added bonus.

StaxMan
+1  A: 

I'm not aware of any tool but I feel it's always good to have some comments in the code if it is to be maintained by someone else in the future. At least, it's good to have header blocks for classes and methods detailing what the class is meant for and what the method does. But yes, it is good to keep the comments as minimal as possible.

+1  A: 

I prefer to use comments to explain

  1. what a class\function is intended to do,
  2. what it is not supposed to do,
  3. any assumptions I make that the users of the class\function should adhere to.

For the users of vi editor the following plug-in is very helpful. We can define templates for class comments, function comments etc.

csupport plug in

Canopus
"what it is not supposed to do" must result in pretty large comments :-)
paxdiablo
yes, and you would end up with more lines of comments than code :)
Shree
+11  A: 

In general, how many lines of comments is recommended for a file with around 100 lines of code?

Enough to make your intent clear and to explain any unfamiliar idioms used. There's no rule of thumb, because no two 100 lines of code are the same.

For example, in C#, a property can be given setters and getters like this:

public int ID { get; set; }

Now I hadn't even seen any C# until I joined StackOverflow two weeks ago, but that needs no comment even for me. Commenting that with

// accessor and setter for ID property

would just be noise. Similarly,

for( int i = m ; i < n; ++i) { // "loop from m to n" is a pointless comment

char* p = getP() ; // set p to getP, pure noise.
if( p  ) // if p does not eqaul null, pure noise

int a &= 0x3; // a is bitwise or'd with 0x303, pure noise
              //  mask off all but two least significant bits, 
              //less noisy but still bad
              // get remainder of a / 4, finally a useful comment

Again, any competent coder can read the code to see what it's doing. Any coder with basic experience knows that if( p ) is a common idiom for if( p != 0), which doesn't need explaining. But no one can read your intent unless you comment it.

Comment what you're trying to do, your reason for doing it, not what the code is plainly doing.

On edit: you'll note that after 11 days, no one has commented on intentional error in one of my example comments. That just underscores that that comment is pure noise.

tpdi
// get remainder of a / 4, finally a useful comment... But in that case it's much better to create a useful function like and use it like in "int a = GetDivisionRemainder(a, 4);" However, I agree with your explanation about the role of comments.
Daniel Daranas
Agreed. But if we're bit twiddling, it's usually because we're in a tight loop, where calling a function is cost-prohibitive.
tpdi
+3  A: 

This is a subject which can be taken to extremes (like many things these days). Enforcing a strong policy sometimes can risk devaluing the exercise (i.e. comments for comment's sake) most of the time, IMHO.

Sometimes an overreaching policy makes sense (e.g. "all public functions must have comment blocks") with exceptions - why bother for generated code?

Commenting should come naturally - should compliment readble code alongside meaningful variable, property and function names (etc).

I don't think there is a useful or accurate measurement of X comments per Y lines of code. You will likely get a good sense of balance through peer reviews (e.g. "this code here should have a comment explaining it's purpose").

I'm not sure about auto-comment tools for C/C++ but the .Net equivalent would have to be GhostDoc. Again, these tools only help define a comment structure - meaning still needs to be added by a developer, or someone who has to interpret the point of the code or design.

RobS
+1  A: 

There are no good rules in terms of comment/code ratios. It totally depends on the complexity of your code.

I do follow one (and only one) rule with respect to comments (I like to stay flexible).

The code show how things are done, the comments show what is done.

Some code doesn't need comments at all, due to it's obviousness: this can often be achieved by use of good variable names. Mostly, I'll comment a function then comment major blocks withing the function.

I consider this bad:

// Process list by running through the whole list,
// processing each node within the list.
//
void processList (tNode *s) {
    while (s != NULL) {         // Run until reached end of list.
        processNode (s);        // Process the node.
        s = s->nxt;             // Move to next node.
    }
 }

since all you're doing there is writing the code thrice. I would prefer something like:

// Process list (or rest of list if you pass a non-start node).
//
void processList (tNode *currentNode) {
    // Run through the list, processing each node.

    while (currentNode != NULL) {
        processNode (currentNode);
        currentNode = currentNode->nextNode;
    }
 }
paxdiablo
Makes good sense.
Shree
+4  A: 

My personal ideal is to write enough commentary so that reading just the comments explains how and why a function is intended to be used. How it works, should usually come out from well chosen variable names and clear implementation.

One way to achieve that, at least on the comment side, is to use a tool such as Doxygen from the beginning. Start coding each new function by writing the comment describing what it is for and how it should be used.

Get Doxygen configured well, have document generation included as a build step, and read the resulting documentation.

The only comment template that might be helpful would be one that sketches in the barest beginning of the Doxygen comment block, but even that might be too much. You want the generated documentation to explain what is important without cluttering it with worthless placeholder text that will never get rewritten.

RBerteig
+1  A: 

You guys may argue about but i realy believe in it:

Usually , You don't have to write comments. Simply as that. The code has to be written in such way that is explain itself , if it doesn't explain itself and you have to write comments , then something is wrong.

There are however some exceptional cases:

  1. You have to write something that is VERY cryptic to gain performence. So here you may need to write some explanation.
  2. You provide a library to some other group/company , It is better you document its API.
  3. There are too many novice programemers in your organization.
A: 

I say that generally comments are a bad smell. But inline code documentation is great. I've elaborated more on the subject over at robowiki.net:

Why Comments are Bad

PEZ
+3  A: 

Commenting code is essential if your auto generating your documentation (we use Doxygen). Otherwise it's best to keep it to a minimum.

We use a skeleton for every method in the .cpp file.

//**************************************************************************************************
//
/// @brief 
/// @details
/// @param  
/// @return
/// @sa 
//
//**************************************************************************************************

but this is purely due to our documentation needs

Gayan
Here is a genuine question - why does that documentation block go in your implementation file, and not your interface file? I always put mine into the interface, so users can see the documentation with the function declarations, instead of having to "code-dive" in order to get the documentation. But I'd like to hear your take on it.
Tom
We've divided the documentation up and put them in the header and implementation file. The documentation in the header is placed at the beginning (revisions) and end (introduction to the class) and the declarations are left as is, the notion being that anyone could get a high level understanding of what the class does by going through the header and for information about a specific method one should go through the implementation.I prefer to have my headers as clean and concise as possible. But I guess it comes down to personal choice.
Gayan
A: 

I concur with everyone about self-documenting code. And I also agree about the need for special comments when it comes to documentation generation. A short comment at the top of each method/class is useful, especially if your IDE can use it for tooltips in code completion (like Visual Studio).

Another reason for comments that I don't see mentioned here is in type-unsafe languages like JavaScript or PHP. You can specify data types that way, although hungarian notation can help there as well (one of the rare cases for using it properly, I think).

Also, tools like PHPLint can use some special type-related comments to check your code for type-safety.

Vilx-
+1  A: 

I wouldn't be so rude to say that comments are excuse for badly programmed code like some people above, nor to say you don't need them.

It also depends on your editor and how do you like to see your code in it, and how would you like others to do that.

For instance, I like to create regions in C#. Regions are named collapsable areas of code, in some way commented code containers. That way, when I look at the editor, I actually look at pseudo code.

#region Connect to the database
   // ....
#endregion

#region  Prepare tables

   #region Cache tables ...

   #endregion


   #region Fix column names ...

   #endregion

#endregion

This kind of code is more readable then anything else I know but ofcourse, it needs editor supporing custom folding with names. (like Visual Studio editor, VIM... ). Somebody will say that you can achieve the similar if you put regions into procedures but first, you can't always do that, second, you have to jump to the procedure to see its code. If you simply set hotkies to open/collapse the region you can quickly see the code in it while scrolling and reading text and generally quickly move over the hierarchy of regions.

About line comments, it would be good to write code that autodocuments itself, but unfortunatelly, this can't be said in generall. This ofcourse depends on projects, its domain and its complexity.

As a last note, I fully suggest in-code documentation via portable and language indepent tool, like for instance NaturalDocs that can be made to work with any language around with natural syntax that doesn't include XML or any kind of special formating (hence the name) plus it doesn't need to be installed more then once.

And if there is a guy that don't like comments, he can always remove them using some simple tool. I even integrated such tool in my editor and comments are gone via simple menu click. So, comments can't harm the code in any way that can't be fixed very fast.

majkinetor
Trap for unwary players: please don't use words like above and below - your entry may move (hopefully right to the top, but then you're only calling the questioner rude :-).
paxdiablo
A: 

There are no metrics you can sensibly use for comments. You should never say x lines of code must have y comments, because then you will end up with silly useless comments that simply restate code, and these will degrade the quality of your code.

100 lines of code should have as few comments as possible.

Personally, having used them in the past, I'd not use things like doxygen to document internal code to the extent of every function and every parameter needing tagged descriptions because with well factored code you have many functions and with good names, most often these tagged descriptions don't say any more than the parameter name itself.

markh44
A: 

My opinion - comments in source code is evil. Code should be self documented. Developers usually forget about reading and updating them.
As sad Martin Fowler: "if you need comment for lines block - just make new function" (this not quote - this phrase as I remember it).

It will be better to keep separated documentation for utility modules, basic principles of your project, organization of libraries, some algorithms and design ideas.

Almost forget: I was used code comments once. It was MFC/COM - project and I leave links from MSDN howto articles near non-trivial solutions/workarounds.

100 lines of source code - should be understandable if not - it should be separated or reorganized on few functions - which will be more understandable.

Is there a tool to generate a skeleton for comments on the Unix platform for C++?

Vim have plugins for inserting doxygen comments template, if you really need this.

bb
+2  A: 

The rules I try to follow:

  • write code that is auto-documented: nice and clear variable names, resist the temptation of clever hacks, etc. This advice depends a lot on the programming language you use: it is is much easier to follow with Python than with C.

  • comment at the beginning to guide the reader so that they know immediately what they are to expect.

  • comment what is not obvious from the code. If you had trouble writing a piece of code, it may mean it desserves a comment.

  • the API of a library is a special case: it requires documentation (and to put it in the code is often a good idea, especially with tools like Doxygen). Just do not confuse this documentation intended for users with the one which will be useful for the maintainers of the library.

  • comment what cannot be in the code, such as policy requirments that explain why things are the way they are.

  • comment background information such a the reference to a scientific article which describes the clever algorithm you use, or the RFC standardizing the network protocol you implement.

  • comment the hacks! Everyone is sometimes forced to use hacks or workarounds but be nice for the future maintainer, comment it. Read "Technical debt".

And don't comment the rest. Quantitative rules like "20 % of the lines must be comments" are plainly stupid and clearly intended only for PHBs.

bortzmeyer