Myths about code comments
It seems to me getting good at writing comments is an under-appreciated part of a Programmer's development. However, I feel that this is a part of programming that's almost as important as writing code itself. So, here are some of the biggest misconception about comments:
Comments are free
This is an assumption that most of us make at one time or another. Comments aren't actually executable code, therefore they aren't maintenance costs, right? As it turns out, this isn't true. When you update the code that the comment references, you usually have to update the comment as well. Unfortunately, this myth is actually true most of the time. After enough time staring at a comment, it typically becomes "noise" that you tune out. Thus, comments have a nasty habit of not being up-to-date.Comments make code more readable
This is by far the most pervasive myth that I've encountered. If anything, comments make code less readable. Nine times out of ten, I ignore comments unless I'm stumped. In fact, I'm tempted to make emacs hide all comments unless I explicitly expand them. Comments don't make code more readable. They are ways to compensate for code not being readable.You should comment every function, method, class, and module
How many times have you seen docstrings like this?def get_x(self): """ This method gets x. """This is about as close to being a canonical "bad comment" as you can get, and yet people who should know better still do it. Why? Because they feel that they should document every function or class. The reality is that documenting something that needs no documentation is universally a bad idea.

Good to know that others feel the same way.
def random_method(arg)
# This is an awesome method
return 4
end
@Peter - I suppose my example of comparing lines of code was a bit simplistic, because I agree with you for the most part. I do disagree that comments should be limited to the WHY though. Perhaps a better way to say it would be "If you must comment, make sure to point out why you did something." There *are* times when the WHAT isn't clear and you need to both explain the WHAT and WHY you need to explain the WHAT.
@Kurtid - That's Python. If the first expression of a function is a string, it's a "docstring", which is used to generate pydocs. You can also leave inline comments like your example as well.
Perhaps you're missing an easier way?
Also, code with two many obvious comments tends make me ignore the rest of the code's comments. Please don't comment just because commenting everything is "best practice". Choose your comments carefully.
Now, as far as the beauty/ugliness of that way of documenting functions, I suppose that's a matter of opinion.
I generally think in an OO system, you would make one comment to describe the general function of the class in general, ensure your methods are "intent revealing", and then only comment the gotchas and special cases.
These special cases are the ones that you either do not have time to refactor, or really dense complicated code that cannot possibly be simplified.
The only other time I think comments are appropriate are for Docs... Java Doc for instance.
I really appreciate your description of comments as code smells. I think I whole heartedly agree with this.
Brian Kernighan has a similar quote: "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."
I highly appreciate self documenting principles (naming variables and functions according to what they do etc) but the key is to use it judiciously. Not just follow the philosophy carte blanche.
I don't always do it right:)...but I try.
And then there is picky teachers. They want them in proper format. Two tabs from left and if more than one line they have to be enclosed in proper comment block. Why? This is for our own ease. Aren't they? Am I writing an essay on fall of roman empire?
How about you shouldn't be in this job if you cant figure out a block of code with a general guiding comment in the beginning.
In past/present, I have been forced to comments like the one below and not to forget that i lost marks on my second assignment cause I thought such a descriptive variable name doesn't need any explanation.
double acceleration. // this stores acceleration
double vf; // final velocity
double vi; // initial velocity
No really tell me why do I need to comment in a program that calculates the time taken for a stone to hit the ground in a free fall.
You're just spouting without support.
Personally, I'd just like to understand exactly when and how comments are useful based on evidence.
My opinion is that comments are useful, BUT, often times we developers get in to a bad habits where the signal to noise in the comments becomes very low to the point they are ignored and left for dead in the source. For example your "get_x()" function is self describing, yet on the other hand, it does not fully document the expected behaviour of the function. For example, should get_x be thread safe? When is the result from get_x valid? What does it return when it is improperly accessed? Is it up to the caller to ensure that the preconditions have been met, or will the function itself perform validation of those conditions? etc... These are mundane questions that developers don't seem to think about enough!
This is a separate issue from commenting code, which should be used to explain the code you actually wrote. Many languages have conventions for writing documentation within their comment syntax, but this is still a case where there are two distinct uses.
That also makes the Python docstring example a bit of a problem case: docstrings can be viewed without viewing the code. So, while "This method gets x" is nonsense, something like "this method returns multiplication factor" may make sense. However, that probably wouldn't make sense as a comment.
Also, your introduction is contradictory and misleading.
Comments should be used as much as possible (but not overused) in most scenatios.
At any rate, its far better to have "too many" comments in the code, rather than too few!!!
I agree with the spirit and intent of your post.
If you haven't picked it up, you might check out "Clean Code: A Handbook of Agile Software Craftsmanship". It is a good read, and has a section that covers code comments quite well.
All of my code is so readable I never have to add a comment. Just as there is an extreme that all code must have comments, there is this extreme (found much more often in my almost 20 years of experience) that a given developer thinks none of their code needs to be documented - that if you can't figure it out you must be brain damaged. Combine that with people who don't write readable code and you have a much worse situation than too much code comments.
Like any other rule of thumb, commenting code is meant to be applied with judgement and common sense. It is obvious to most devs that you don't need to comment everything. A little less obvious maybe that you should comment code which doesn't have an obvious intent.
Yes, comments generally have to be maintained, just like code, but that doesn't mean you shouldn't use comments - it means you should maintain them, including removing them if they are not needed.
I have seen a lot of Java beans that just had a lot setters and getters. When these were documented using JavaDocs, the write just entered 'sets XYZ' and 'gets XYZ' for setter and getter of XYZ. Lazy and obviously not needed. Now if 'XYZ' is 'customerName' or 'customerAddress' then okay, still no comment needed. But if 'XYZ' is 'factor', then tell me what 'factor' is - is it a fudge factor, is it a multiplier for some computation? If I don't know the domain, and the property isn't obvious, then give me a clue here - just a couple of words is better than nothing.
In general, whenever I see posts like this, they are either in response to criticisms like above where the poster didn't comment some code that wasn't obvious and/or wasn't readable to mere mortals like me, and/or it was in response to some org that mandates every little line of code must be commented. Use your judgement. There are more important things to rant about.
I know it's probably harder to come up with good examples of comments than bad ones, but there are hundreds of open-source projects out there you could glance through and I know at least a dozen of them are well-commented. It shouldn't be too difficult to find some comments that perfectly compliment the code they were written for.
Other than that though, it's good to see someone taking on those oft parroted beliefs about comments.
My dream is basically how Word tracks annotations.
This is completely bullshit. There are often complex code sections implementing complex algorithms where you can not put everything into code. Comments can be very helpful to explain clearly why the code is as it is. This has nothing to do with badly written code. A line of code is cleary not expressive enough for complex scenarios. Overgeneralizing that any code must be self documenting is just stupid.
> Why Put Comments In Code?
> 1) Make the code easier to read
> 2) Engage the linguistic side of your brain
The second point is especially compelling.
But you should try to remove code comment as much as possible by making the code more readable/maintainable/simple by refactoring it.
What do u think about the below code
-------------------------------------------------------------------------
// this is the calculation of calculating transaction total;
$a = ($cost*$amount)+0.5;
$toal = $k-$a *(0.3-$4m);
-----------------------------------------------------------------------
$this->calcuateTotal($total, $amount);
private function calcualteTotal ($cost,$amount){
$a = ($cost*$amount)+0.5;
return $k-$a *(0.3-$4m);
}
obviously second block is more readable/maintainable/simple and it doesn't need any code comments due to rafactored it with extract method.
Obviously code comment might be a smell. It tells from where the smell is. otherwise we need to find where the smell comes.
Sometimes code is just too complex and/or generic that it requires comments. But code is often better written with appropriately named functions and variables, than a bunch of comments describing over and again what the functions and variables point to. Also when using OO code, comments are redundant.
easy: use short variable names and functions just like natives.
not function doThisRedunantFnordAlghortihm(NARFnotZOONK:String, NOTNARFbutZOONK:Array) but function fnords(string:String,array:Array). avoid globals and shit. most of the times comments are an excuse for long code. the comments dont make the code shorter... they make it longer (if you havent notice) and longer means more complex than before. therefore it makes no sense to comment a very COMPLEX(fnord) part of code. either you can deal with it or you can take a look into the documentation.
Please, for the sake of the programmer who comes after you, comment your intent more often than you think you need to.
On comments: I do believe that there is a balance to be maintained. Clearly, obvious functions such as pure getters and setters of object variables do not need commenting. However, even here you might need to comment any assumptions and you certainly need to comment any derived members.
Methods of any complexity need to be documented as to what is the intended function, the assumptions made (32/64 bits anyone?), and valid range of inputs/outputs - especially if input is not validated. In addition, algorithms used and any special tricks need to be fully documented.
I also strongly feel that comments on variable declarations are needed. While "float acceleration;" may seem descriptive and thus not deserving of a comment, in fact it is missing the most critical information for a physical value - the units. Is the acceleration in m/s^2 or inches/fortnight^2.
Going further, my view is that all current programming languages have failed in one of the most basic aspects of their job of representing the real world in a useful set of abstractions. No programming languages allows any attachment of units to variable or constant declarations - I should not have to guess the units used, and the compiler should validate correct assignment of units throughout the system (including automatic conversion as needed - if an int can be converted to a float, than an inch should be convertible to a meter without me having to explicitly code for it!). Think about the numeric value in your code - how many are truly dimensionless values?