General best practices: commenting code

In summary, the conversation discusses the best practice for commenting code, with some arguing that comments should be placed before the subprocedure to explain its purpose and others arguing that comments should be placed within the subprocedure to clarify specific lines of code. Overall, the consensus is that comments should be used sparingly and only when necessary, with the most important being comments that explain the input/output and purpose of the code.

Is it better practice to comment before a sub procedure or within?

  • comment before

    Votes: 4 14.8%
  • comment within

    Votes: 1 3.7%
  • both

    Votes: 17 63.0%
  • I have a different system

    Votes: 0 0.0%
  • I have no system, I comment how I feel like it

    Votes: 5 18.5%

  • Total voters
    27
  • #1
DaveC426913
Gold Member
22,480
6,146
When you're commenting your code (and I don't care what language you're writing in), do you comment *before* the subprocedure or *within* the subprocedure? What is the best practice?

eg.

Comment before:

// loop through the following code
for i=1 to 10
---(some code)
---...
---// check truth of x
---if (x) then
------(some code)
---else
------(some code)
---end if
next

Comment within:

for i=1 to 10
---// looping through this code
---(some code)
---...
---if (x) then
------// x is true
------(some code)
---else
------// x is false
------(some code)
---end if
next

I can see advantages and disads of each.

I understand that the post obvious answer is "It doesn't matter, as long as it makes the code understandable." But I like consistency.
 
Technology news on Phys.org
  • #2
Both: The outer comment explains what the procedure does. The inner comments explain what each part of the procedure is for. If you clog the outer comment with too much info it makes quick reading of code difficult---when scanning code you should get enough info about code execution from the outer comments to know the framework of the program. The inner comments are used to explain the how's and why's of the functions/variables which isn't important when looking at the big picture.
 
  • #3
One other variant of "inside" (if your language allows) is on the same line, e.g.
for i=1 to 10 // looping through this code

One advantage of this is that the code and comment are a little more tightly bound to each other... and show up together when grepped.

With more editors supporting "folding", I wonder how commenting styles may be influenced by this.
 
  • #4
I am new to programming. If I have a big related section then I will comment before on the entire thing. If something is small I put it on the same line, or right after.

Edit.. After looking at a recent program of mine I put some comments before and some after.

For example:

//start of something
{
something
}
//end of something

I guess whatever feels natural for me anyways.
 
Last edited:
  • #5
As a general rule, I don't think it matters as long as it's clear, to whoever reads the code, where the comment belongs.

(Of course the specific examples of a comments given in post #1, e.g. "check truth of x" to explain "if (x)", would be pointless comments.)

However, if you are using some type of automated documentation system (such as Doxygen for the C++ language), you are forced to put certain types of comment before the thing they refer to.
 
  • #6
FWIW - this ain't an "art form", folkks. There is a body of research on the subject - a fairly large body.

There are best practices for commenting. None of which has been encapsulated by the responses so far. Largely because it's not amenable to a one liner. For example, variable naming conventions are REALLY important to code commenting. Then there is the idea of self-doumenting code.

Large development houses require all programmers and analysts to have read
(for example):

McConnell, S., 'Code Complete', Microsoft Press 2004.

-- before they start work.

I wrote a small white paper on good coding practices once. I can post it here if you have the patience to read the durn thing.
 
  • #7
jim mcnamara said:
I wrote a small white paper on good coding practices once. I can post it here if you have the patience to read the durn thing.
That would be swell, yes.
 
  • #8
This is a small white paper on code style and readability of code.
About 1/3 of it deals with comments.

All of it is aimed at C code, but it applies anywhere.
 

Attachments

  • codestyle.zip
    25.1 KB · Views: 215
  • #9
A clever non-programmer I am looking for feedback from actual programmers to see if my request specific to comments in code is reasonable. A generic question, my main concern is that of SQL Stored Procedures (SP).

Want current programming resource to include a brief English language comment toward the beginning of any new SP created that defines the purpose / function of the object.

Example: Truncates log files generated during the XYZ process, or Automates steps A, B and C to load batches into System X.

Is this reasonable? Notice most examples do not include the purpose of the object.
 
  • #10
jim mcnamara said:
This is a small white paper on code style and readability of code.
About 1/3 of it deals with comments.

All of it is aimed at C code, but it applies anywhere.

Thanks for the paper, it looks great!

But wait, you think cyclomatic complexity is meaningful?
 
Last edited:
  • #11
DaveC426913 said:
When you're commenting your code (and I don't care what language you're writing in), do you comment *before* the subprocedure or *within* the subprocedure? What is the best practice?

...

I can see advantages and disads of each.

I understand that the post obvious answer is "It doesn't matter, as long as it makes the code understandable." But I like consistency.

I was taught that you comment at the beginning to define the inputs, outputs, side-effect, etc. But also anywhere else that needed clarification (i.e. where the code wasn't "obvious").

CS
 
  • #12
stewartcs said:
I was taught that you comment at the beginning to define the inputs, outputs, side-effect, etc. But also anywhere else that needed clarification (i.e. where the code wasn't "obvious").

That's how I do it.
 
  • #13
I use two styles of comments. I put large comments, almost prose-like, above each major block of code. I set these apart from the code with blank lines and perhaps rows of slashes or other devices. These block comments explain in plain english what the following block is going to accomplish and how it works.

Then, I put individual line comments above any tricky or especially important lines within the block.

- Warren
 
  • #14
In my not so humble opinion:

If the purpose of a function or method is known, and you cannot follow the code, at least one of these are true:

- You do not understand the concepts used (ie, you cannot follow the math)
- The code is too complex and should be subdivided into more functions or methods
- The code is badly written (ie using non descriptive names for variables)

Thus, comments are only needed to explain the input/output of a function or a method.

k
 
  • #15
jim mcnamara said:
This is a small white paper on code style and readability of code.
About 1/3 of it deals with comments.

All of it is aimed at C code, but it applies anywhere.

I have read that thoroughly and indeed it is a good white paper.

Ah, I have spotted some typos also and here I give you the revised version.


Eus
 

Attachments

  • codestyle.zip
    24.9 KB · Views: 425
  • #16
In C# i often comment using regions or not at all and let descriptive class, function and variable names do the talking. Lots of comments can get in the way of reading the code (in my opinion). When looking through someone's code my first step is usually to quickly glance at the comments and then remove all of them. I dislike line-by-line comments (they tend to get unnecessarily lengthy and specific), i prefer a few lines at the top of a function or class that describe the general implementation approach plus any remarks on less intuitive parts of the code.
 
  • #17
When I ran a develpment shop we had comment standards for C, BASIC and FORTRAN plus some other languages you've never heard of.

And job is right: excessive comments get in the way of reading the code.

Without getting into Halstead code metrics, readability of code translates in a big way to vocabulary. An analogy is English class. If you examine Shakespeare's 'Romeo and Juliet' and then look at the King James version of the Bible (both written within a few years of each other) you will find that Shakespeare ransacked the English lexicon, while the writers of the King James version used less than about 6000 English words.

Reading Shakepeare can be an exercise in using the dictionary - all the extraneous effort going into simple comprehension of the text gets in the way of the story. Excessive comments in code do the same thing - they get in the way of the story. Using descriptive consistent variable naming makes it easy to comprehend logic. It keeps the vocabulary count down. Keeping variable scope limited -- ditto.
 
  • #18
jim mcnamara said:
This is a small white paper on code style and readability of code.
About 1/3 of it deals with comments.

All of it is aimed at C code, but it applies anywhere.

Eus said:
I have read that thoroughly and indeed it is a good white paper.

Ah, I have spotted some typos also and here I give you the revised version.


Eus
Thanks, it's great. I use both of commenting types before and after (I'm using c/c++), and the doxygen could recognize them by “//!” (before) and “///<” (after) styles.

But, in my opinion, using comment is not enough, sometimes; I think it's hard to draw a flowchart in cpp files.even; I'd like to add some picture describing more complicated structures. By the way, does someone heard that a code editor support embedded images?

Thanks.
 

1. What is the purpose of commenting code?

Commenting code allows for better understanding and organization of the code. It helps other programmers (and yourself) to quickly understand the code's purpose and functionality.

2. How should I format my comments?

There is no one correct way to format comments, but it is important to be consistent. Some common practices include using single-line comments with // or multi-line comments with /* */. It is also helpful to include a brief description of what the code does and any relevant information.

3. Should I comment every line of code?

No, it is not necessary to comment every line of code. Comments should be used to explain complex or important sections of code or to provide context for the code's purpose. Too many comments can make the code hard to read and cluttered.

4. How often should I update my comments?

Comments should be updated whenever there are significant changes to the code. It is important to keep the comments in sync with the code to avoid confusion. If a section of code is no longer relevant, it should be removed along with its corresponding comments.

5. Can comments slow down my code's performance?

No, comments are ignored by the compiler and do not affect the performance of the code. However, excessive comments can make the code harder to read and understand, which can indirectly affect performance. It is important to find a balance between commenting enough to provide clarity and not over-commenting.

Similar threads

  • Programming and Computer Science
Replies
30
Views
4K
  • Computing and Technology
Replies
3
Views
2K
  • Programming and Computer Science
Replies
4
Views
905
  • Programming and Computer Science
Replies
14
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
1K
  • Programming and Computer Science
3
Replies
75
Views
4K
  • Programming and Computer Science
2
Replies
36
Views
3K
  • Programming and Computer Science
Replies
19
Views
961
  • Programming and Computer Science
Replies
7
Views
1K
Back
Top