Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Assuming a comment won't fit (or can't go) on the line it applies to, should one write the comment before the code or after?

Well, wherever future readers will best understand the comment's scope. In other words, wherever most programmers/scripters put such comments.

So where do most programmers/scripters put a comment: before or after its code?

If your answer applies only to specific languages, please indicate which.

And if you can cite an accepted spec or guide that supports your answer, so much the better.

share|improve this question

closed as primarily opinion-based by Oded May 30 at 10:26

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.

1  
Considers what happen when you put it after. Programmer read the code. Tell himself WTF this is doing ??? See the comment. Read the code again. Sometime understand it or give up. So be nice and avoid the part 1 and 2 by putting it on top. –  deadalnix Dec 22 '11 at 20:05
    
@deadalnix, thanks, that seems to be the gist of Dipan Mehta's answer as well. (Thanks also to all answerers thus far, and +1 to each.) –  msh210 Dec 22 '11 at 20:14

13 Answers 13

up vote 13 down vote accepted

I would either comment inline or before the code the comment should apply to. The sense of comments is to get some basic understanding what the code does, without the need to read the code itself. So it makes much more sense to place the comments before the code it describes.

Microsoft says it would be a good programming practice to begin procedures with a small comment. (They don't mention commenting after procedures) MSDN The link is about VisualBasic but it applies to the most programming languages i think.

share|improve this answer
    
Checkmark, as this is the only answer (thus far) that clearly answers the question, which sought not personal preference but standard operating procedure, in that it cites MSDN. –  msh210 Dec 23 '11 at 15:21
    
@msh210: So you prefer a Microsoft preference to the personal preferences of other good programmers? BUT you DO know how Microsoft got the Hungarian Notation all wrong as a standard? Yes? Do you? Only trust common sense, don't always run with the horde or follow the biggest bull. –  Falcon Jan 30 '12 at 20:14
    
@Falcon, I've never heard of Hungarian Notation, and I suspect MSDN's preference was at least the result of a bunch of MS employees' input; answers here, by contrast, are individually authored. –  msh210 Jan 30 '12 at 20:50

I prefer comments to be above the code they refer to, it just makes more sense to tell a person reading code about what is coming up rather than trying to refer to previous code to explain that some messy lines of code fixed some bug that was tricky so don't touch it.

share|improve this answer

I think code is generally read top-to-bottom. If nothing else, muscle memory would cause me to associate a comment with the next line of code beneath it.

share|improve this answer

Typically the comment should be on the TOP of the row following the same indentation as the work. For example, comments above the body of the functions, and one liner comments just above the start of a critical algorithm.

The reason is, when someone starts reading it, it becomes obvious question that why something is done in such a way; where as the person doesn't know till what point one needs to scroll for the answer. If it is on top, it is right there to see.

share|improve this answer

To borrow some ideas from technical writing (at least in the English language), things such as notes and cautionary warnings are typically placed before the instruction or section that the note or cautionary warning applies to.

I don't see why code can not be considered a form of technical writing - each block is an instruction. Like the English language, most programming languages are read left to right, top to bottom. Comments are notes about the code - they might identify errors to fix, or things that a future developer might need to be aware of.

Following this relationship, it seems more appropriate to put the comment above the block of code that it refers to.

share|improve this answer

A comment may need to go either above or below a piece of code, depending on what kind of comment it is: if it gives an ultra-brief explanation of what the code does, then it needs to precede the code; if it elaborately clarifies a technical detail about how the code works, then it needs to follow the code.

Luckily, a comment can go either above or below a piece of code, and still leave no doubts about which piece of code it pertains to, by making proper use of blank lines. Of course, programmers who do not pay attention to the use of blank lines will not know what I am talking about; if you are one of those, please skip this answer and move on with your life. But programmers who pay attention to blank lines know very well that blank lines are used to divide code up into logical entities. So, if you see the following:

[blank line]
/* comment */
{ code }
[blank line]

You know that the comment belongs to the code, and that it tells you what the code does. Whereas, if you see the following:

[blank line]
{ code }
/* comment */
[blank line]

Again you know very well that the comment belongs to that code, and it is a clarification about how the code does what it does.

share|improve this answer
    
As I always say: your downvote without an explanation does not help me become a better person. Love you too! –  Mike Nakis Dec 23 '11 at 14:01

Having the comment appear before the code helps the reader have a context for the code they're about to encounter. Much more humane than throwing the code at them and explaining after they're already confused.

share|improve this answer

I'm not actually a big fan of comments. During a software engineering course, I was introduced to the idea of self-documenting code. The code is the only 100% guaranteed correct documentation of itself - comments need to be updated, carefully constructed and relevant, otherwise they are traps that can be worse than no comment. It wasn't until I started working in a C++ shop with a strict style guide and meaningful naming conventions that I truly internalized this concept.

Sometimes comments are necessary. A lot of times, careful variable naming, meaningful use of white space and grouping, and a meaningful logical organization of the code itself eliminates the need for the comment.

This really is a negation of the pretense and validity of your question, as opposed to an answer for the question you had. I still think it is relevant and may help you, and I wasn't a jerk. If not, the -1's will dominate me.

share|improve this answer
6  
Self-documenting code can answer "what" and "how", but no matter how well-written, code by itself can seldom answer the question "Why?". If there's a comprehensive requirements document, you can sometimes find the answer there. Otherwise, comments are often all you've got to explain why the code needs to do what it does. –  Ed Staub Dec 22 '11 at 23:24
1  
I don't agree. As @EdStaub says, commenting answer a different question, at a different level. Also code is not necessarly open-source. And even when it is, I don't want to read a framework source code to know how to use it. –  rds Dec 23 '11 at 10:52
3  
You have obviously never dealt with hardware (or interfacing with poorly written software, either). I recently finished writing a specialized class to talk to a rather obscure (and cranky) motor controller. It has all sorts of weird requirements for interfacing. Short of having literally one function per line, there is no way to make the code understandable without commenting. –  Fake Name Dec 23 '11 at 11:41
2  
@Brian, "Why" questions are often very fine-grained - e.g., getting around bugs in an API, and/or explaining that something that looks wrong is actually correct. Those are just a couple of examples. I wouldn't make comments be a comprehensive requirements document. But neither would I try to explain the rationale for every little implementation detail in a requirements spec (or even a design spec, for that matter) either. –  Ed Staub Dec 24 '11 at 1:40
1  
@codesparkle - I agree that comments used as an excuse to avoid refactoring are generally bad. However, this does not mean that all comments are bad, just that comments abused in such a manner are. The fact is, there are a number of situations where comments are really the best option to clarify odd coding requirements. –  Fake Name Dec 26 '11 at 13:54

OK, I'll make the "after" case: the code should always be the primary documentation, while the comment (which has no semantic meaning) is like a parenthetical explanation. So putting the comment below the code that needs explanation leaves the code as the prime explanation, and just uses the comment for clarification. For instance,

if(date == CHRISTMAS){
     //Deliver presents
     val (nice, naughty) = partition(boysAndGirls);
     prepSled();
     findRudolph();
     putOnRedSuit();
     ...
}else{
     //Not Christmas, build toys
     monitorElves();
     ...
}

If you put the comment before the test, the reader is going to tend to read the comment as the primary thing and may not read the code closely, not realizing that they've been misled:

 //Check to see if it's a leap year
 if(year % 4 == 0){ ... }  
share|improve this answer
5  
Both your code blocks have comments before the code they're commenting. –  msh210 Dec 23 '11 at 0:32
    
your own comments negated your "after case" hehe :) hugs and +1 for making it a christmas themed example –  Ahmed Masud Dec 23 '11 at 3:42
1  
@msh210 I see my comments in the first example as commenting on the if(christmas) test, not as being "about" the following functions (that is, they are saying "what does it mean that we are here?") They precede a code block, but I've never seen code that had ...code(); code(); /* comment explaining preceding block */ } and didn't take the question that way –  Larry OBrien Dec 23 '11 at 20:52

Try to comment only where really necessary; the code should try to be self-documenting whenever possible.

That being said, the placement can depend: If you use a separate line for the comment, put it before the actual code. If you have it on the same line, put it after.

// this workaround is required to make the compiler happy
int i = 0;

Vs.

int i = 0; // make the compiler happy

But never:

int i = 0;
// this workaround is required to make the compiler happy

share|improve this answer
    
Reread the question: it specifies it's asking about a comment on a separate line. –  msh210 Dec 23 '11 at 0:29
1  
@msh210 This is a perfect answer. "write comments before". It is even more detailed and give a possible reason why you might think they are after "Except when they are short and are at the end of the line." –  rds Dec 23 '11 at 10:47

Comments above is best.

if you have to include comments and your code is not self-explanatory, then I would rather not be confused by a block of code, then see "ahh, that's what it was supposed to do".

Code can (and should) be "self documenting", but if you have to read and understand every line of code to understand how a method works. If a summary/ comment found in the last of method then it will be lot of coding time is spent searching for the chunk of code that we wish to edit. By using a summary comment on each block, I can quickly zero in on the block that is relevant to my task.

When i have goggled about this topic, i found that most computer-readable documentation systems (Doc XML, Doxygen, Java doc etc) expect the comment to come before the code it relates to - it's better to remain compatible with that standard.

I am also agree with the SO thread - Should we be adding comments after code blocks, rather than before? ..

I'd also rather know up front...

share|improve this answer

I often convert comments (mine as well as written by others) into trace level log statements. This typically makes it much easier to understand where to place it.

    // Return an empty list if we failed to retrieve anything
    // I convert above to:
    logger.trace("Return an empty list if we failed to retrieve anything");

An additional advantage is that when going gets tough I can turn on log tracing and get more detailed execution log.

share|improve this answer

So where do most programmers/scripters put a comment: before or after its code?

In many years of programming using a variety of languages, I don't recall seeing any code in any language where a comment is placed on a new line after the code to which it refers. In the US, at least, the de facto standard is commenting either before the code or on the same line following the code. Writing your comments after the related code invites a drug test, a psychiatric evalutation, and/or a date with a pair of pliers and a blow torch.

The only exception I can think of is a comment marking the end of a previously commented section, like this:

// BEGIN CRITICAL SECTION
lock(&myMutex);

doSomeThreadUnsafeStuff();

unlock(&myMutex);
// END CRITICAL SECTION

Jef Raskin wrote a well-considered essay on comments that's worth a read. He doesn't say whether he puts his comments before or after the code, but he does say that he never puts them inline, and I'd bet a lot of money that he doesn't put them after either.

share|improve this answer

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