A coworker of mine believes that any use of in-code comments (ie, not javadoc style method or class comments) is a code smell. What do you think?
34 Answers
Only if the comment describes what the code is doing.
If I wanted to know what was happening in a method or block, I would read the code. I would hope, anyway, that any developers working on a given project were at least familiar enough with the development language to read what is written and understand what it is doing.
In some cases of extreme optimization, you might be using techniques that makes it difficult for someone to follow what your code is doing. In these cases, comments can and should be used to not only explain why you have such optimizations, but what the code is doing. A good rule of thumb would be to have someone else (or multiple other people) familiar with the implementation language and project look at your code - if they can't understand both the why and the how, then you should comment both the why and the how.
However, what's not clear in the code is why you have done something. If you take an approach that might not be obvious to others, you should have a comment that explains why you made the decisions that you did. I would suspect that you might not even realize that a comment is needed until after something like a code review, where people want to know why you did X instead of Y - you can capture your answer in the code for everyone else who looks at it in the future.
The most important thing, though, is to change your comments when you change your code. If you change an algorithm, be sure to update the comments with why you went with algorithm X over Y. Stale comments are an even bigger code smell.
- 85,641
- 18
- 207
- 307
This is particularly irritating to hear at the moment, I spent some time this weekend looking at very well-named, very clean, uncommented code implementing a research algorithm (one that isn't actually published). I'm high-level familiar with it, the guy sitting next to me was the inventor, and the code was written a few years ago by someone else. We could barely follow it.
Your co-worker is not experienced enough, obviously.
- 8,560
- 1
- 34
- 41
Comments should explain why, not how.
How type comments are usually better dealt with using refactoring. Personally, I usually avoid comments in favor of refactoring.
Before:
# convert to cents
a = x * 100
# avg cents per customer
avg = a / n
# add to list
avgs < avg
t += 1
after:
total_cents = total * 100
average_per_customer = total_cents / customer_count
track_average(average_per_customer)
- 1,264
- 12
- 20
I declare your co-worker a heretic! Where are my heretic-burnin' boots?
Obsessive commenting is bad and a maintenance headache, and comments are no replacement for well-named methods, classes, variables, etc. But sometimes putting why something is the way it is can be immensely valuable for the poor idiot who has to maintain the code in six months -- particularly when that poor idiot winds up being you.
Some actual comments from the code I'm working on:
// If this happens, somebody's been screwing around with the database definitions and
// has removed the restriction that a given alarm may have only one entry in the
// notifications table. Bad maintenance programmer! Bad! No biscuit!
// If an alert is active on our side but inactive on theirs, that might mean
// they closed the alert. (Or that we just haven't told them about it yet.) The
// logic comes later; for now, we'll just compile it in a list.
// If we know for a fact that an alarm isn't getting through, we're going to whine pretty
// aggressively about it until it gets fixed.
- 8,693
- 5
- 42
- 46
Ideally, code should be so well coded that it should be auto explicative. In the real world, we know that also very high quality code needs sometimes commenting.
What you should absolutely avoid is "comment-code redundancy" (comments that don't add anything to code):
i++; // Increment i by 1
Then, if there's a good (and maintained/aligned) code design and documentation, commenting is even less useful.
But in some circumstances comments can be a good aid in code readability:
while( foo )
{
if( dummy )
{
}
else // !dummy
{
}
} // end while( foo )
Don't forget that you have to maintain and keep in sync also comments... outdated or wrong comments can be a terrible pain! And, as a general rule, commenting too much can be a symptom of bad programming.
- 7,337
- 2
- 43
- 76
Categorically defining a method or process as a "code smell" is a "zealotry smell". The term is becoming the new "considered harmful".
Please remember that all of these sort of things are supposed to be guidelines.
Many of the other answers give good advice as to when comments are warranted.
Personally I use very few comments. Explain the purpose of non-obvious processes and leave the occasional death-threat to anyone that might be considering altering things on their own that required weeks of tuning.
Refactoring everything until a kindergartner can understand it is likely not an efficient use of your time, and probably will not perform as well as a more concise version.
Comments don't affect run time,so the only negative issue to consider is the maintenance.
- 8,380
The primary issue here is the meaning of the term "code smell".
Many people (including you, I think) understands a code smell to be something close to an error or at least something that needs to be fixed. Perhaps you think of it as a synonym to "anti-pattern".
This is not the meaning of the term!
The code smell metaphor originates from Wards Wiki, and they stress:
Note that a CodeSmell is a hint that something might be wrong, not a certainty. A perfectly good idiom may be considered a CodeSmell because it's often misused, or because there's a simpler alternative that works in most cases. Calling something a CodeSmell is not an attack; it's simply a sign that a closer look is warranted.
So what does it mean that comments are a code-smell: it means that when you see a comment, you should pause and think: "Hmmm, I sense a hint that something could be improved". Perhaps you can rename a variable, perform the "extract method"-refactoring -- or perhaps the comment is actually the best solution.
That is what it means for comments to be code smells.
EDIT: I just stumpled upon these two articles, which explains it better than me:
- 290
In some cases, no amount of good naming, refactoring etc. can replace a comment. Just look at this real-world example (language is Groovy):
response.contentType="text/html"
render '{"success":true}'
Looks strange, doesn't it? Probably a copy-paste-error? Cries for a bugfix?
Now the same with comments:
// DO NOT TOUCH THE FOLLOWING TWO LINES; the ExtJS UploadForm requires it exactly like that!!!
response.contentType="text/html" // must be text/html so the browser renders the response within the invisible iframe, where ExtJS can access it
render '{"success":true}' // ExtJS expects that, otherwise it will call the failure handler instead of the succss handler
- 28,434
I think the rule is quite simple: imagine a complete stranger seeing your code. You probably will be a stranger to your own code in 5 years. Try to minimize the mental effort to understand your code for this stranger.
- 5,649
A good idea to have the right comments is to start with writing comments.
// This function will do something with the parameters,
// the parameters should be good according to some rules.
myFunction(parameters)
{
// It will do some things to get started.
// It will do more with the stuff.
// It will end doing things with the stuff.
}
This allows you to extract methods easily to even get rid of the comments,
just let the code tell these things! See how this is rewritten (cut/paste) in a very nice way:
// This function will do something with the parameters,
// the parameters should be good according to some rules.
myfunction(parameters)
{
var someThing = initializedWithSomething;
doSomethingWith(someThing);
doMoreWith(someThing);
endDoingThingsWith(someThing);
return someThing;
}
// This function will do some things to get started,
// the parameters should be good according to some rules.
doSomethingWith(parameters)
{
parameters.manipulateInSomeWay();
... etc ...
}
... etc ...
For things that can't be separated just don't extract methods and type the code under the comments.
This is what I see as an useful way to keep commenting to a minimum, it's really useless to go commenting each line... Only document a single line if it's about a magic value initialization or where it makes sense.
If parameters are used too much, then they should be private members in your class.
- 8,219
I think the answer is the usual "It depends" one. Commenting code just to comment code is a smell. Commenting code because you're using an obscure algorithm that's an order of magnitude faster saves the maintenance programmer (usually me 6 months after I wrote it) half a day of poking through the code to determine what it's doing.
- 660
- 4
- 8
// Dear me in the future. Please, resolve this problem.
or
// You think this code was written by somebody else.
// No, it wasn't. You ([some name]) did it.
- 631
Code comments are definitely not a "code smell". This belief typically comes from the fact that comments can become stale (out of date) and can be difficult to maintain. However, having good comments which explain why the code is doing something a certain way can (and usually is) important for maintenance.
Good comments make it easier to understand what the code is doing and, more important, why it is doing it a particular way. Comments are meant to be read by programmers and should be clear and precise. A comment that is hard to understand or incorrect isn’t much better than having had no comment at all.
Adding clear and precise comments to your code means that you don’t have to rely on memory to understand the “what” and “why” of a section of code. This is most important when you look at that code later on, or someone else must look at your code. Because comments become part of the textual content of your code, they should follow good writing principles in addition to being clearly written.
To write a good comment, you should do your best to document the purpose of the code (the why, not how) and indicate the reasoning and logic behind the code as clearly as possible. Ideally, comments should be written at the same time as you write the code. If you wait, you probably won’t go back and add them.
Sams Teach Yourself Visual C# 2010 in 24 Hours, pp 348-349.
- 1,045
- 1,479
- 1
- 11
- 8
If the code has been written in a particular way to avoid a problem present in a library (both a third-party library, or a library that comes with the compiler), then it makes sense to comment it.
It also make sense to comment code that needs to be changed in future versions, or when using a new version of a library, or when passing from PHP4 to PHP5, for example.
- 4,004
- 8
- 44
- 53
Even the most well-written book still likely has an introduction and chapter titles. Comments in well-documented code are still useful to describe high-level concepts, and explain how the code is organized.
- 2,069
Of honorable mention is the anti-pattern:
It's my impression that sometimes FLOSS license preamples are frequently used in lieu of file documentation. The GPL/BSDL makes a nice filler text, and after that you seldomly see any other comment block.
- 2,333
I disagree with the idea that writing comments to explain the code are bad. This completely ignores the fact that code has bugs. It might be clear what the code does without comments. It's less likely to be clear what the code is supposed to do. Without comments how do you know if the results are wrong, or they're being used incorrectly?
The comments should explain the intent of the code, so that if there is a mistake, someone reading the comments+code has a chance of finding it.
I generally find myself writing inline comments before I write the code. This way it's clear what I'm trying to write code to do, and reduces getting lost in an algorithm without really knowing what you're trying to do.
- 896
I'll answer with a question of my own. Can you find the bug in the uncommented code below?
tl;dr: The next person to maintain your code might not be as godlike as you are.
[org 0x7c00]
main:
mov ah, 0x0e
mov bx, string
call strreverse
call print
stop:
jmp $
strreverse:
pusha
mov dx, bx
mov cx, 0
strreverse_push:
mov al, [bx]
cmp al, 0
je strreverse_pop
push ax
add bx, 1
add cx, 1
jmp strreverse_push
strreverse_pop:
mov bx, dx
strreverse_pop_loop:
cmp cx, 0
je strreverse_end
pop ax
mov [bx], al
sub cx, 1
add bx, 1
jmp strreverse_pop_loop
strreverse_end:
popa
ret
print:
pusha
print_loop:
mov al, [bx]
cmp al, 1
je print_end
int 0x10
add bx, 1
jmp print_loop
print_end:
popa
ret
string:
db 'Boot up', 0
times 510 -( $ - $$ ) db 0
dw 0xaa55
- 2,588
Comments that are put in because someone thinks it's ok to have 700 lines in one method are a smell.
Comments that are there because you know if you don't put in a comment, someone will make the same mistake yet again are a smell.
Comments put in because some code analysis tool demands it are also a smell.
People that won't ever put in a comment, or write even a little help for other developers are also a smell. I'm amazed at how many people won't write stuff down, but will then turn around and acknowledge they can't remember what they did 3 months ago. I don't like to write docs, but I like to have to tell people the same thing over and over again even less.
- 5,214
You have to keep a balance between code and comments... Usually I try to add some comments that resume a block of code. Not because I won't be able to understand the code (well, that also), but because I can read faster my own code and locate specific sections where the important stuff it's happening.
Anyway, my own personal criteria is "when in doubt, comment". I prefer to have a redundant line than a completely cryptic line that I'm not going to be able to understand. I can always remove comments on a code review, after a while (and I usually do)
Also, comments are quite helpful adding "caveats" like "Be careful! If the format of the input is not ASCII, this code will have to change!"
- 1,339
Reading this I am reminded on something that I first read (from a longer list, preserved by taking photocopies) some decades back:
Real programmers don't write comments - if it was hard to write it should be hard to read
A rather older smell methinks.
- 7,843
I think code commenting gets a very poor start to life. I don't know about these days, but when I was first being taught programming at school I got assignments of the nature of "Write a program that prints the numbers one to ten on separate lines. Make sure you comment your code." You'd get marked down if you didn't add comments because commenting your code is a GOOD THING.
But what is there to say about such a trivial process? So you end up writing the classic
i++; // add one to the "i" counter.
just to get a decent grade and, if you've any nous at all, instantly forming a very low opinion of code comments.
Code commenting is not a GOOD THING. It's a SOMETIMES NECESSARY THING, and Thomas Owens in the top answer provides an excellent explanation of the situations in which it's necessary. However, these situations rarely crop up in homework-type assignments.
In many ways, adding a comment should be considered a last-resort choice, when what needs to be said cannot be said clearly in the active parts of the programming language. Although object naming can go stale, various human and computer lack-of-feedback mechanisms make it easy to forget to maintain comments and consequently comments go stale much more quickly than active code. For that reason, where a choice is possible, changing code to make it clearer should always be preferred to annotating unclear code with comments.
- 111
There's a big fundamental difference between comments and code: comments are a way for people to communicate ideas to other people, whereas code is primarily meant for the computer. There are many aspects in "code" that's also only for humans, like naming and indentation. But comments are written strictly for humans, by humans.
Therefore, writing comments is every bit as difficult as any written human communication! The writer should have a clear conception of who the audience is, and what kind of text they will need. How can you know who will read your comments in ten, twenty years? What if the person is from a completely different culture? Etc. I hope everybody understands this.
Even inside the small homogeneous culture I live in, it's just so difficult to communicate ideas to other people. Human communication usually fails, except by accident.
Of course comments are a code smell...
every programmer knows we all eventually turn insane due to the amount of work, debugging, or just plain madness we run into.
"Do this!" your project manager says.
You respond, "It can't be done."
They say, "Then we will find someone else to do it."
You say, "OK, well maybe it can be done."
And then spend the next X number of days.. weeks.. months.. trying to figure it out. Throughout the process, you will try and fail, and try and fail. We all do this. The true answer is there are two types of programmers, those that comment and those that don't.
1) Those that do are either making their own job easier by documenting for future reference, commenting out failed routines that didn't work (the smell is not deleting them after finding the one that works.), or breaking up the code with comment formatting to hopefully make it a bit easier to read or understand. Seriously, I can't blame them. But in the end, they snap and then you have this:
// dammit this code sucks! swear! curse! i hate it! i am going to write something here to vent my anger!!!!
2) Those that don't are either pretending to be a superhero, or are living in a cave. They simply have reckless disregard for others, themselves, and could care less about the code, or what meaning it could possibly have for later.
Now don't get me wrong.. self-documenting variables and functions can avoid this entirely.. and trust me you can never do enough code-cleanup. But the simple truth is that as long as you keep backups, you can ALWAYS delete comments.
- 748
I'd argue that not using some comments in your code is a code smell. While I agree that code should be self documenting as much as possible, you hit a certain point where you are going to see code that makes no sense regardless of how well the code is written. I've seen some code in business applications where the comments are pretty much mandatory because:
- You need to do something on a case by case basis and there's no good logic for it.
- The code will likely change in a year or two when the laws are changed and you want to find it again quickly.
- Someone edited the code in the past because they didn't understand what the code was doing.
Also, company style guides might tell you to do something a certain way - if they say that your could should have comments outlining what blocks of code in a function is doing, then include the comments.
- 11,304
No one said this so far in this thread, so I will:
Type names, variable names, function names, method names and comments are just metadata about your code, and has nothing to do with the machine code that the compiler generates (except the names of the exported and debug symbols of course).
Type names and variable names are your nouns, function and method names are your verbs, with these you describe steps to be done. Comments are for everything else.
Some examples:
double temperature; // In Kelvins.
/**
* Returns true if ray hits the triangle
*/
bool castRayOnTriangle(Triangle t, Ray r)
{
//...
if (determinant == 0)
{
/* The ray and the triangle are parallel, no intersection possible.*/
return false;
}
//...
}
/* X algorithm. Visit http://en.wikipedia.org/... for details.*/
<implementation of something difficult to understand for the layman algorithm. >
Comments may bacome obsolete, if not updated, but variable and function names can become obsolete too. I recently encountered a bufPtr field in a C structure, which has nothing to do with buffers or pointers. And I saw a inflateBuffer function that does not decompress a deflated data but a complete GZIP file... These are as annoying as outdated comments.
- 1,913
It doesn't seem like too many answers consider programming in teams. I'm a senior developer and I tend to write comments aimed at explaining what is otherwise simple for me to understand.
I see it as a form of posthumous team communication or education. I encourage the team to look through code they are using, but maybe haven't written to understand it better.
A couple of examples just from this week (PHP code):
//Pattern for finding jpeg photos
//Case insensitive pattern for jpg and jpeg
const PATTERN_PHOTO = "*.{[jJ][pP][gG],[jJ][pP][eE][gG]}";
I'd hope the name PATTERN_PHOTO would be helpful later in code to explain what it does, but without the comments how clear would it be to a junior developer what this specific pattern does?
Same set of code:
//Ignore . and .. directories in Linux
if($file != "." && $file != "..")
There's an expectation that our developers know PHP, but not that they understand the Linux OS we are using for hosting.
So, I find these comments to actually increase the overall efficiency of our team for the very little time it takes to write them.
- There's less cases of people rewriting code simply because they don't understand how it works. "I didn't understand how it did what it was supposed to, so I fixed it." Seriously, I've had to deal with this before.
- There are less questions asked about individual pieces of code. Answering the questions just once, usually requires looking up the code and the time for me to re-familiarize myself with it. And sometimes I'll get the same question from more than one person weeks apart. (Yes, it would be on things as simple as the examples above)
- Other developers are encouraged and guided to learn on their own. I'd expect that if they came across
//Ignore . and .. directories in Linuxthey'd likely hop on Google and would suddenly understand Linux a little bit better.
- 368
Here's my rule-of-thumb:
- Write the code and store a short summary of the code in a separate document.
- Leave the code alone for several days to work on something else.
- Return to the code. If you can't immediately understand what it's supposed to do, add the summary to the source file.
- 3,136
I have to agree with your coworker. I always say that if I comment my code, it means that I'm worried that I won't be able to figure out my own code in the future. This is a bad sign.
The only other reason I sprinkle comments into the code is to call out something that doesn't seem to make sense.
Those comments usually take the form of something like:
//xxx what the heck is this doing??
or
// removed in version 2.0, but back for 2.1, now I'm taking out again
- 793
No, comments are not a code smell, they are just a tool that can be abused.
Examples of good comments:
// I think this is in cm. Further investigation needed!
// This is a clever way of doing X
// The list is guaranteed to be non-empty here
- 5,159
However code that cannot be understood at all it a much bigger code smell…
Please give me clean code to work on, however
if that is not an option, I would rather have “dirty” code with comments
than dirty code without comments.
- 4,623
Most of the words have been taken out of my mouth. But I suppose to sum it all up: the point of comments is to give a high-level description/explanation of what the code is doing.
Moreover, here are a few examples of how I use comments:
- as headings, to indicate the general purpose of a section of code
- to note where I have cribbed code from and thereby avoid plagiarism
- occasionally at the ends of blocks, to remind of what block they're the end of
- to point out that code that may look suspicious is what's intended (e.g. those odd times when a switch case falls through)
- to explain the maths behind an algorithm
- 155
Code comments giving, where applicable, units of function arguments and returns, structure fields, even local variables can be very handy. Remember the Mars Orbiter!