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.

I was taught in university to write comments for our programs. As I write comments, I feel like I have a better organization and understand the programs better.

However, I am in a company where most of the code I encounter doesn't have comments. Why would a programmer not write comments? Are there are any objective reasons? Do you think comments are annoying when you read others' code? I don't write comments either, and I can think of some reasons why not:

  1. Because I can already easily understand the program.
  2. My boss won't care how my program gets the job done.
  3. Nobody is likely to pick up my program after I am gone.

The purpose of comments is usually to include explanations for the program, however, I found that in my company, comments are used to cover obsolete code instead. For example:

/* Obsolete code */
New code

What is your opinion on commenting? Should we do it? Or does it depend on the situation?

share|improve this question
47  
If your code needs commenting it is too complicated. Refactor and make it more obvious what the code does. Code should be self commenting. The only comments allowed should be to explain why the code does something, not what it does it, if there is some non-obvious implied business logic. Commenting out obsolete code is stupid, delete it. You should use version control to keep code history. –  Qwerky Aug 4 '11 at 9:20
34  
Totally disagree with @Qwerky here - from a management perspective it makes much more sense to have your code fully commented so that it is still manageable easily without you. Code is not self commenting in most languages. –  Rory Alsop Aug 4 '11 at 9:58
7  
Let the commenting flame wars commence ... But just before that I would just like to point out the Code Complete II section 32.3 - The Commento. –  AlexC Aug 4 '11 at 10:29
27  
Commenting-out obsolete code is even worse than the issue with no comments. Don't these people have version control? If code is no longer used, delete it. –  Daniel Roseman Aug 4 '11 at 10:33
7  
@Rory, But isn't that like saying 'I understand everything I say, but does someone else?' If you are the only one understanding what you are trying to say, you have a communication problem. The same applies to code. If we both code java, we both should know the java language, and there for be able to understand each others code. It is of course possible to write java so that other java developers want be able to understand, but thats bad code. –  Vegar Aug 4 '11 at 11:55
show 13 more comments

18 Answers

As many people have noticed huge amounts of comments are hard to maintain. Besides, some people think that with proper variable names, method names and design patterns, the code should document itself and you should be able to read it (more or less) fluently. In that case you should only comment "harder" or "performance-intensive" pieces of code where it is not straightforward what's going on by just looking in a single or double pass the code.

I would have added some other reasons but they don't apply to a company-wide code conduct.

share|improve this answer
add comment

Comments should be done on code "paragraphs". Unless you have a dense one liner, you very rarely need a comment to explain a single command. Anyone familiar with the langauge in question should be able to understand it just by reading it, or looking it up.

What you are trying to document is the logic flow of the code, not the gritty details. For example:

writer = csv.DictWriter(open(args.out, 'wb'), output[0].keys(), dialect='excel')
writer.writeheader()
for row in output:
    writer.writerow(row)
writer.close()
del writer

All by it self, what does this mean? We have to dig into each line of code and put it together to understand what is going on, but we still don't know why. What if this was longer, for a more complicated idea? Compare it to this:

# Dump found entries into a CSV file for Excel
writer = csv.DictWriter(open(args.out, 'wb'), output[0].keys(), dialect='excel')
writer.writeheader()
for row in output:
    writer.writerow(row)
writer.close()
del writer

Anyone who checks this out afterwards understands both the content and objective of this code, without the need to dig into it and learn what it does.

share|improve this answer
30  
"Code Paragraphs" should be extracted into their own methods, and given descriptive names. –  Adam Jaskiewicz Aug 4 '11 at 18:21
5  
+10 for this. Selective comments are very helpful. Yes, code can be 'self documenting,' but by adding one line you can understand a whole block of code at a glance, instead of working through each line to figure out everything that it does. –  Steven Aug 4 '11 at 18:30
5  
@Adam Jaskiewicz so when you call all of those functions one after another in the function they were removed from, you end up with obfuscated confusion. Should I have to examine all of the c standard library functions to have a broad overview of a program someone else wrote? –  Spencer Rathbun Aug 4 '11 at 19:55
4  
@Adam Doing so would needlesly complicate code. I split up methods based on major function, not microtask. If you follow that rule then most projects will have 4-5x as many methods as nessesary. –  TheLQ Aug 8 '11 at 5:29
5  
I don't understand why "dump found entries into a csv file for excel" isn't a method name. A 6 line method dumpToCsv(output); is easily understandable in the scope of the calling method, the scope of the method and doesn't require comments that can rot. –  StuperUser Nov 2 '12 at 13:29
show 5 more comments

Comments are a slippery subject, and you'll find loads of flamewars on the web about the right amount of comments a developer should write.

Personnally I like to relate the need for comments to the "technicality scale" of the code you want to comment. On one end of the scale you have close-to-the-metal code using lots of primitive types, dealing with the system, or code that underwent obscure tweaks for performance reasons. The extreme opposite on the scale is purely domain-related code (usually in the business/domain layer), which in my opinion has to be as expressive as possible, with class, variable and method names reflecting real-life concepts of your domain.

Low-level technical code may require quite a lot of comments, because its purpose might be concealed behind non-obvious technical manipulations, complex algorithms, or primitive types usage. A basic example is if a method returns an int (which I wouldn't encourage, but sometimes lower-level operations have to do that), without a Javadoc-like comment on the method you have no way of knowing upfront if the returned int is an error code, an ID...

Conversely, the more domain-related you get, the fewer comments you need, because the names of objects you manipulate should be self-explanatory.

One additional thought: don't underestimate the power of unit tests as a replacement for comments for code documentation purposes. A well-written unit test immediately tells you what the responsibility of the method is AND is compile-safe AND executable.

share|improve this answer
add comment

I'd say it depends on the situation. When the code is not too much esoteric and the variable names are well chosen, so that the code is "self documenting", then comments might not be necessary. But when the intent is not clear just by looking at the code (for example when using some obscure math theorem), then a good comment explains the why.

Remember that even if they don't compile, comments need to be maintained to follow the code. Imagine a comment explaining the wrong thing because the code changed, and the developer not being able to figure it out. So too many comments means more unnecessary work. (Is too much or not enough better? That's another debate)

As for your case, do other developers need to take a look at each other's code sometimes? Did you never hear one of them (or yourself) saying "What does this code do? I don't understand anything!". If it is the case, maybe a well placed comment is needed.

share|improve this answer
add comment

I worked once in a company that discouraged too much use of comments. Though this was for Ruby on Rails. Ruby is a very expressive language and the Ruby on Rails framework dictates quite clearly where things belong and what they are good for. So using comments in a controller to explain what a method is good for would have been needless. So this may depend on context and language you use. Much can be already explained by using descriptive names for methods and variables. It may even force you to keep methods small and have a single, clearly defined purpose. If it becomes difficult to find a good name for a method, it's most likely because the thing is doing too much and should be split in smaller parts.

Leaving old code and commenting it out is a bad habit. That's what a version control system is used for. If you want to see the former state of a file, use the functionality of Git or SVN or whatever you use. Otherwise you have to scroll through pages and pages of old stuff that makes not much sense in the actual context anymore.

share|improve this answer
4  
Agreed - always remove obsolete code, otherwise you run the risk of it being accidentally available for an attacker to use. And it looks messy and takes up space:-) –  Rory Alsop Aug 4 '11 at 10:56
1  
+1, especially to the last point. At my current job everyone is too afraid to remove old code, even when it's commented out, "in case we need to revert". They don't quite grasp that's the point of SVN (nor do they use SVN correctly). –  Wayne M Aug 4 '11 at 12:03
show 2 more comments

The only comments I like are the ones explaining why the current design is bad and how to improve it.

Outside those "this is why this sucks" comments, if you can't understand what it does by looking at the code and reading/running the tests then there is no hope.

share|improve this answer
add comment

Too many comments are much worse than too few. They take time to write, and even more time to maintain. Throughout the life of a project, code will always reflect what the program does, comments will be inaccurate the instant the code changes. Once the intent to the code does not match the comment, you are on a slippery downhill slope. Comments are not tested by compilers for correctness, so incorrect comments cannot be detected and corrected by the programmer unless huge amounts of attention to detail, where it makes little difference, is made.

In my experience new programmers often overcomment code with useless comments that add no value. Extreme cases such as this are common

int x ; // Integer x 
// Copy the string bob into fred making sure not to overflow the buffer. 
strncpy(bob, fred,sizeof(bob));  

(The error is intentional to make a point)

However devs putting in too few comments is just as common......

share|improve this answer
12  
I highly disagree with that sentiment, that bad comments are better than no comments. Bad comments actively mislead/lie about what the code is doing. This is the same reason why I am pretty obsessive about renaming methods even if they're already working; if the name no longer reflects what the method is used for then it is lying. –  jhocking Feb 17 '12 at 15:31
4  
When doing code reviews, I make people refactor their naming and extract functions/methods until there is no need for comments, thus no need to keep comments in sync, thus no bad comments, which are worse than no comments at all. –  Jarrod Roberson Feb 17 '12 at 16:17
show 1 more comment

If the company doesn't require comments in code, most programmers won't comment because of their laziness, and they will find a clever excuse why comments are never necessary.

On the other hand, sometimes the comments are really unnecessary (for example at trivial getters and setters in Java), and if company creates an official comment-writing policy, programmers are at risk that they will be forced to write comments even in such situations. An ambitious manager can also mandate very complicated comment templates.

This results in a situation where some programmers do write comments and silently curse the laziness of their colleagues, but do not risk discussing this topic openly, because things could get worse.

share|improve this answer
add comment

Job security is a valid reason. If no one but you understands the code, you cannot be fired.

Note to those that have not read Sarcasm for Really Smart People: Not correctly commenting code is unprofessional.

share|improve this answer
1  
but you can not advance as well –  BЈовић May 17 '13 at 12:39
add comment

In my personal experience, comments are useful in two cases:

  1. explain the code to the next programmer (if you leave)
  2. explain the code to yourself (when you are dealing with thousands of files and can't remember the logic behind them).

The second point is most important and mostly neglectable by some companies, thinking they need comments only in case 1, and if that case isn't in their plans then comments aren't as well..

Plus, isn't programming about making decisions all the time? How could you remember the motives behind a decision if you don't write it down?

I recommend writing comments (even against the company flow), because your productivity is somehow depending on it.

share|improve this answer
4  
Think of the incredibly hacky, totally uncommented metaprogramming techniques in Boost (and soon to be in C++11). That code is so incredibly convoluted that it needs comments, lots and lots of comments. But it isn't. Figuring out what that code does and how it works takes a lot of time, much of which could have been saved with a choice comment or two. –  David Hammen Aug 4 '11 at 19:28
show 2 more comments

From my perspective, comments should generally be limited to method level comments (Javadoc or .NET XML type comments) for the generation of documentation later and TODO comments. Beyond that, I think in most cases commenting is superfluous, time-consuming, and slightly annoying. If you really think the person who comes behind you can't figure it out, then refactor it or at least put it in its own method with a method level comment.

share|improve this answer
add comment

In broad terms, we write software to create or add value.

Comments, though, are not part of the binary/executable part of the software, they are a part of the source code aspect of the software. Thus, they are supposed to add value to the source code.

Comments that do not add value are pointless and wrong.

When comments do not match what the code is doing, then the software is wrong and the value is lost.

Writing comments has a cost. If the comments are to have a net positive value then the cost of writing the comments must be less than the value one reaps from them.

Everything else is just details.

share|improve this answer
add comment

Comments are fine, as long as they are used only when necessary and they explain something that is not obvious. The examples of mattnz make that clear. There is nothing that is not obvious in that part of the code since it is just using already documented features. Thus for example by executing man strncpy you can find out everything about this function. Not putting any comments in such code is much better and less confusing for other programmers.

Document only the complex parts of your code, and if necessary the input/output and arguments of your functions/methods; the latter is useful if you want to export your API using a documentation system. Do not forget that when a part of the code is updated, the comments must also be updated, thus the maintenance time is longer; which means that your comments should really worth the effort.

share|improve this answer
3  
I agree overall, though I wouldn't say that maintenance of comments makes maintenance times "much longer." Longer, yes, but as long as you update your comments when you change the code, it doesn't take that long. Aside from that, the rule of thumb I use is "if you have to think about what it does, it's probably a good place for a comment." (Because if you wrote it and still have to think about it, remember the poor sap that will look at it later, even if that sap is you.) –  Shauna Aug 4 '11 at 14:28
show 1 more comment

Comments are useful whenever the purpose of the code is not immediately obvious.

Maybe the code could be made clearer, maybe not.

Maybe it's obvious to you, but wouldn't be to someone else.

It's a judgement call.

(I get a bit tired of the anti-comments religionists; who often come dangerously close to throwing out the baby with the bathwater. They may be deliberately overstating their case, having understood the problem, but others will just take it on board and add one more absolute to their ignorance. By all means, fight for clearer code; when you've won THAT battle, start fighting against comments.)

share|improve this answer
3  
I find it a good rule to follow that if the code reviewer asks me why I did something (and after a conversation we agree that it was the right choice) then the maintainer will probaly have the same question and the why needs to be explained. This is often true even when the maintainer is me but six months or more have passed. This is especially true when the requirement was not something we would normally do. Honestly, how many devs go back and research all the old requirements to see why we did something? –  HLGEM Feb 17 '12 at 16:36
show 1 more comment

The problem begins with people who are of the opinion that comments explain what code does. Then it's a very easy leap to "why bother commenting" and then to "we don't comment here."

Instead, comments should explain why the code exists.

/* setting foo to 1 here so that biz doesn't run too many times 
 * changed from 6 on 3-Aug-11 for ticket 1234
 */
foo = 1; 

This is, I think, something that should be (but isn't) explained in school.

share|improve this answer
4  
Your SVN/git/whatever logs should cover what you changed it from and when, so there's no need for that. It's pretty obvious that you're setting foo to 1; I'd call foo something like "bizRuns" and include a comment such as // biz should only run once [ticket 1234]. –  Adam Jaskiewicz Aug 4 '11 at 21:30
2  
ok, so a 'better' comment would be /* setting foo to 1 as using 0 makes the MIS system crash with a 0-based data export. */ there are lots of weird reasons that need commenting, like why the unit statuses in the app I worked on couldn't handle the value 17. –  gbjbaanb Jan 16 '12 at 23:27
show 2 more comments

Why would a programmer not writing comment, if there are any objective reasons?

Comments take time to write and can sometimes be put on hold for other higher priority work. Haven't you had cases where it was more important to "git-r-done" than comment what was done way back when?

Do you think comment annoying when you read other's code?

Comments can be useful but how many places will let you spend hours writing comments that aren't adding immediate business value?

My overall view is comments are good in moderation. Too much or too little can be a big problem.

share|improve this answer
add comment

There are mainly two categories of comments:

  • Comments explaining code
    As other have mentioned, code and comments tends to drift apart. You may leave a comment before a block of code, but when time goes by, the code changes, and no one updates the comment to reflect the changes. The comment becomes a lie.
    If you really feel that a block of code needs a comment to explain the intention of the code, what you could do instead, is to extract the block of code into a method and give it a name. The name will then become the explanation. And method names don't drift the same way comments does. No one likes to call a method called 'GetData' that actually saves some data in stead. Either the developer would change the name of the method, or see that the change they are gonna make doesn't belong there at all.
    There are some things that can't be part of a name, though. Like why did you choose this algorithm over the other one, or why what seems like a more obvious solution to a problem is no good in this particular case and so on.
    There are other cases where a name want contain all there is to know about the code. If you have a good set of unit tests, (and you should), the test suite will be part of the explanation of both intention and inner workings of the code. And naming your tests is as important as naming your production code.

  • Comments disabling code
    When writing new code, its often 'comforting' to keep the old algorithm around for reference, After a while, the code tends to be cluttered with small or larger code blocks disabled by comments. It makes the code harder to read, and the reader must consider if the code is relevant or not.
    There are no need for this type of comments, since every edit to a file should be kept in a source control system anyway. If you need to check how an algorithm was in an earlier version, you should be able to go there and have a look. Every check in should have either an comment describing the intention of the code commit, or an link to a bug report or some thing like that.

Robert C. Martin has written a book called 'Clean Code'. He devoted a whole chapter on comments in code. The book is a good one, and worth both money and time.

share|improve this answer
add comment

They want your code to make sense in and of itself. In the real world, that is not always possible. But it is better to strive for the former and find a way to cope with the latter.

share|improve this answer
add comment

protected by Telastyn Dec 30 '13 at 13:51

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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