15

I'm wondering if people have a standard format for comments in their code. Not things like xml comments for a method or class but rather comments within a method.


See also:

Is there a standard (like phpdoc or python’s docstring) for commenting C# code?

2
  • Now I understand the question much better: Even tho he says he doesn't want XML comments like used for methods and classes. He is looking for the same system for within the body of a method. Apr 22, 2009 at 20:50
  • 2
    er... why are people voting to close this? Are people not noticing that this question is NOT a duplicate of the question linked in the See also section?
    – Powerlord
    Apr 22, 2009 at 20:50

25 Answers 25

29

You should really consider a couple things to make good comments beyond formatting.

  1. Do not simply restate what the code is doing. For example,
 // Start the services
 StartServices();

is a frigging terrible comment!

  1. Describe why. Why is the code doing what it's doing? What's the business assumption or algorithm step?

  2. Format your comments for maximum readability. Tab them properly, leave spaces where necessary, etc.

  3. If someone has already started commenting in a standard way, don't break that standard.

  4. Check this article on MSDN about writing effective comments: http://msdn.microsoft.com/en-us/library/aa164797.aspx

2
  • Just a few minutes before my answer. :) Glad someone else said describe the "why" Apr 22, 2009 at 20:47
  • after rereading the edited question I realized my understanding of it was way off. Apr 22, 2009 at 21:45
8
// I usually write comments like this

Where I work it is required to use standard xml comment style for most of the declarations (classes, methods, some properties) (we use C#).

Sometimes you can see header/footer comments in use.

/****************************************************/
// Filename: Customer.cpp
// Created: John Doe
// Change history:
// 18.12.2008 / John Doe
// 14.01.2009 / Sara Smith
/****************************************************/

/* Here goes a lot of stuff */

/****************************************************/
// EOF: Customer.cpp
/****************************************************/

Something like this was used at one of my old places of work. In my opinion too much of unnecessary stuff. Change history is nicely seen these days through a version control system.

In many good software shops there are internal guidelines as to when and how to write comments. Documents are typically referred to as "Source code style policy" or something. It is very important to adhere to one common style in commenting the code.

Of course this commenting hype shouldn't go too far as to comment every little piece of code, especially the obvious ones.

/// <summary>
///     Handles the standard PageLoad event
/// </summary>
/// <param name="sender">
///    Event sender
/// </param>
/// <param name="e">
///    Event arguments
/// </param>
public void Page_Load (object sender, EventArgs e)
{
    // Do something here
}

This one is a good example of over-obsession with commenting. Something like this adds exactly zero information but only adds noise to the source file. And we have to do it at work as required.

My personal opinion is add comments when you have something to say or explain, not just for the sake of commenting everything.

3
  • WTF? - This just had 3 upvotes out of no where, now 0 just as fast. Apr 22, 2009 at 20:35
  • 1
    Change history? That's what your VCS is for. Seriously.
    – Tanktalus
    Apr 22, 2009 at 20:39
  • +1 for source code style policies. None here and I wish there were. Apr 22, 2009 at 20:54
5
/**
 * block comments to document a method for javadoc go like this
 * @param
 * @return
 * @exception BTKException
 * @see BTK
 */
1
  • Well, not within a method as the question states.
    – Joey
    Apr 22, 2009 at 20:34
4

Comment on the line above the code (block) that does what you're describing

// This is a comment.
Some code goes here

Avoid doing stuff like

// ----------------
// IMPORTANT COMMENT
// ----------------

And I avoid using the

/* comment */

And perhaps most importantly, clean up comments! A comment that describes non-existent functionality is worse than no comment at all.

2
  • 3
    There's nothing wrong with /* ... */ style comments. The OCD types might even prefer a logical open/close to a comment (even when only on 1 line) Apr 22, 2009 at 20:49
  • Just because you disagree with a convention that I use is no reason to downvote this. I simply said "I avoid". Why? Because // comments are easier (I've found) to clean up, and/or edit.
    – patjbs
    Apr 22, 2009 at 20:56
4
//For one line, I write them like this

/*
For multiple lines of text
I write them like this
*/

/*
for(multiple lines of code){
  I.WriteComents(With("//"));
  Reason==If(I.Remove('The top begin-quote mark') then
    I.Worry.Not('About removing the close-quote mark');
//*/
4

The problem with comments within a method (rather than in an interface), is that they are actually not meant to be seen by anyone except for people maintaining that method. Therefore, there is no real need for a standard for the comments. They don't get published anywhere, they're not publicly visible, callers will generally never see them.

In general, comments inside code should follow four rules:

  1. They should not state the obvious
  2. They should be consistent with what they describe
  3. It should be clear what they describe (e.g., which line, block).
  4. They should be readable by any future maintainer.

That being said, there is often a tendency to place information that is important to the callers as an internal comment. For example: "OOPS, This doesn't handle negative numbers". Whenever you see an internal comment, reconsider whether the header documentation should be updated, or use a tool that "pushes" the comments to the awareness of function callers (I have a tool like that for Java).

2
/* I will sometimes write
comments like this */
0
2

I can't believe we missed the REM keyword.

Though to be fair, it's for REMARK not COMMENT.

1
  • 1
    I almost added it, but thought I'd be dating myself. Apr 22, 2009 at 21:09
2
# ----------------------------------
# BIG IMPORTANT COMMENTS IN PERL/SH
# ----------------------------------
2

Comments standards are most useful when the comment will be parsed by an external tool (usualy, a document generator, like javadoc).

In this case, the external tool will state the standards.

For other cases, see How do you like your comments? (Best Practices)

1
//Cheap Debugger

//Response.Write(MySQLStringBecauseINeedToKnowWhatsBroken);
0
' I usually write comments like this
1
  • While I didn't like VB, this is how you comment. Apr 22, 2009 at 20:27
0
<!--How about comments like this!?-->
0

There are packages that will help write and format documentation. They require some specific changes so they can identify classes of comments.

such as doxygen:

http://www.doxygen.nl/manual/docblocks.html

/*! \brief Brief description.
 *         Brief description continued.
 *
 *  Detailed description starts here.
 */
-1
(* Modula-2 comments go like this *)
-1

If you are paranoid and don't use or trust source control, you might do this

// Initials-YYMMDD-fixNo-Start
dosomething();
// Initials-YYMMDD-fixNo-Finish

It makes a bloody big mess, but it gives you some way to rollback changes.

But I'd suggest using source control

-1

There can be religious wars on this subject.

What I try to do, that doesn't cause too much warfare, is

 // explain the purpose of the following statement in functional terms
... some statement ...

The idea is, if I run the code through a program that deletes everything except the comments, what is left is pretty good pseudocode.

Something that's useful as a way to comment out code that you think you might need again is:

 /*
 ... some code ...
/**/

then modify the first line - either delete it, or change it to /**/

 /**/
... some code ...
/**/
2
  • 1
    I don't agree. The problem with calling comments pseudocode is that people tend to go overboard and comment assignments and loops, and my personal pet peeve - an inline comment to end an if or loop. Apr 22, 2009 at 20:43
  • Yeah, I know. As peeves go, that's livable. My bigger goal was to keep pseudocode up to date with the real code. Apr 22, 2009 at 20:45
-1
/*
 * Brief summary of what's going on.
 */
int code_that_goes_on(int c)
{
     /* and then if I have to remark on something inside... */
     return 0;
}

99% of compilers will support // comments, which is awesome, but that 1% still exists, and it's not too difficult to make life livable for them.

EDIT: The Delphi comment is a bit obtuse, but does point out a real deficiency. I intend this to be a C-specific answer.

2
  • Some compilers don't support the /* blah */ syntax.... Delphi, for example, uses { blah } for block comments. Apr 22, 2009 at 20:37
  • ++ to offset the --. I like to save -- for nasty answers. Apr 22, 2009 at 20:48
-1

I don't think there is a standard for what you are asking. And I don't see how it would add any benefit from /// comments on the method itself.

For creating documentation from your C# classes take a look at Sandcastle.

-1

In C/C++/C#/Java, when I have a comment explaining a block of code:

// comment
code;
more_code;

when a comment is explaining a single line:

code; // comment

I usually use // for single sentence comments and /* ... */ comments for multi-sentence comments.

-1

One comment style in C++/Java etc is this:

// Use // for all normal comments...
// and use multiline comments to comment out blocks of code while debugging:
/*
for(int i = 0; i < n; ++i) {
    // If we only use // style comments in here,
    // no comment here will mess up the block comment.
}
*/

I think it is an interesting point, even if it's not that incredibly useful.

-1

My code is self-documenting. I need no comments.

5
  • You always, always need a comment. Because either we will forget what we did in this file, or we move on, and someone will have to figure it out. We all hate coming to a job, and seeing an app with no comments, and no way to figure it out. jeez.
    – crosenblum
    Feb 11, 2010 at 22:55
  • 2
    @crosenblum That's just wrong. Do you comment simple get/set methods? It's very rare that good code need any comments at all. The exception is when optimization or business decisions lead to non-obvious code decisions. Oct 31, 2012 at 6:59
  • Sadly most of the previous code i've worked with is poorly documented and has no code, no clear functional sections, with clear purposes. In that case you need comments, because the previous programmer left and there is no clue as to what the each code piece does.
    – crosenblum
    Nov 12, 2012 at 1:05
  • 2
    1) I was being sarcastic and 2) if a programmer is that bad, you have a bigger problem than no comments
    – Mike Cole
    Nov 12, 2012 at 20:27
  • :D you should have put a smiley face after your answer so they don't chop your head off :)))
    – Eric
    Jun 24, 2018 at 6:09
-1

I'm surprised that not more people recommended doxygen. It is a good way of documenting code, with the side effect that it can automagically generate html + pdf API documentation at the end of the day.

-1

I prefer commenting this way for function

/**
 * Activates user if not already activated
 * @param POST string verificationCode
 * @param POST string key
 * @return true on success, false on failure
 * @author RN Kushwaha <[email protected]>
 * @since v1.0 <date: 10th June 2015>
 */

public function activateUserAccount() {

//some code here

}

I use single line comment for code descriptions like

//check if verificationCode exists in any row of user table
code here
-1

You might want to at least consider using standard comment formats for the PHP Reflection Class: https://www.php.net/manual/en/reflectionclass.getdoccomment.php

My sites compress html so a comment like // comment here in JS will crash the java script. The specs for using // in PHP is only supposed to be a "short comment" ie: one line. Personally I don't think they should be used for more than one line.

Using them also makes it impossible to compress - or a lot harder to compress than what it should be.

Lastly.

Human interpretation is NOT absolute - a computer code is :)

So if you have a code that needs to or should be read - (Go Nasty) and don't comment it. ie: Force the reader to read the code rather than you relying on their interpretation of your comment.

Not the answer you're looking for? Browse other questions tagged or ask your own question.