31

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?

17
  • 48
    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, 2011 at 9:20
  • 42
    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, 2011 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, 2011 at 10:29
  • 30
    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. Aug 4, 2011 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, 2011 at 11:55

17 Answers 17

47

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......

3
  • but I'd rather have the new coders writing bad comments than no comments whatsoever. When they become good coders, I wouldn't want the 'hack the code in without any comment' bad practice to still be with them.
    – gbjbaanb
    Aug 5, 2011 at 8:24
  • 13
    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, 2012 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.
    – user7519
    Feb 17, 2012 at 16:17
27

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.

10
  • 34
    "Code Paragraphs" should be extracted into their own methods, and given descriptive names. Aug 4, 2011 at 18:21
  • 9
    +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, 2011 at 18:30
  • 8
    @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? Aug 4, 2011 at 19:55
  • 7
    @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, 2011 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, 2012 at 13:29
13

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.

4
  • 5
    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]. Aug 4, 2011 at 21:30
  • good points, Adam. I should have left off with the text and not included a hastily-typed example. <grin>
    – StevenV
    Aug 5, 2011 at 18:50
  • 3
    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, 2012 at 23:27
  • This is when you want to comment, yes I can see that foo has been set to 1, but if you set it to 137 leaving a note saying why it should be 137 would be helpful.
    – Zachary K
    Dec 30, 2013 at 14:22
13

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.

5
  • 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, 2011 at 10:56
  • 2
    +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). Aug 4, 2011 at 12:03
  • Also, figuring out which commented out section is the 'previous' version could be a pain too... Aug 4, 2011 at 16:54
  • My personal "favorite" is the bug tracking system comment: /* #12345 */ something = 42; Yeah, that's NOT helpful. Feb 17, 2012 at 16:20
  • On the other hand, I really love (not sarcastically) the requirement tracking comment referencing back into the requirement that inspired the code. I've used it a few times to find out why something was done a specific way to help me decide if a certain change was viable or not--also when the requirements change being able to track where in the code existing parts of the requirement were implemented is really a time saver.
    – Bill K
    Nov 15, 2014 at 9:27
10

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.)

3
  • 5
    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, 2012 at 16:36
  • As time goes by I use fewer comments than I used to, preferring to use object, function, and variable names that tell the story a much as possible. I do still try and put myself in the place of the poor smuck who will wind up maintaining my code, who will appreicate the odd extra clue for things that aren't crystal clear. Feb 17, 2012 at 16:51
  • 1
    It's all about how long it takes to comprehend the code afterwards. If having a comment makes it quicker for someone else to pick up the code and understand it, you should put them in there. The time taken to write and maintain them is completely irrelevant, most coding time (by far) is spent understanding with existing code and dealing with problems caused by a lack of understanding existing code. If you don't believe me, count the LOC in your project and divide by man hours to see how much actual code is typed an hour over the life of a project--it's not as much as you think.
    – Bill K
    Nov 15, 2014 at 9:34
7

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.

6

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.

2
  • 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, 2011 at 14:28
  • @Shauna I agree with your comment regarding "longer vs much longer" maintenance time. Answer updated, thanks :)
    – sakisk
    Aug 24, 2011 at 19:06
5

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.

4

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.

4

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.

1
  • 3
    but you can not advance as well May 17, 2013 at 12:39
3

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.

3
  • 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. Aug 4, 2011 at 19:28
  • @DavidHammen perhaps they didn't want you to understand it, or at least render it hard for you to figure it out. I'm not aware of the code nor who wrote it, but it is a common practice to ensure people won't meddle with your code or even avoid being fired if your code is in a top-critical area of the company's software.
    – Marco A.
    Dec 30, 2013 at 13:34
  • indeed it's challenging and elegant to have (concise?) code without comments, though I'd classify that for elites. In a structure-organization-team settings, from an engineering perspective, it's more productive to write comments
    – k.honsali
    Jan 24, 2014 at 8:57
3

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.

3

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.

2

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.

1

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.

0

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.

0
0

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.

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