Do you update ancient code comments that are wrong? [closed] - comments

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
G'day,
Inspired by a comment I made in my answer to this question on commenting Perl regexps I was wondering the following.
When you are working on older, old, bloody ancient, code do you update comments that are out of sync with the code or do you just update the code and ignore the comments that are already "miles out" from the reality of the current code?
I guess basically approaching things from the "broken window" syndrome?
BWS basically says that people just say "stuff it" and don't take care to fix errors that are there if they see that people, already involved with the system in question, didn't care enough to fix these sorts of things. A totally pervasive mind set IMHO!
I'd be interested to see what other people "at the coalface" do.
cheers,

I will absolutely fix bad comments.
Sometimes it is just to delete them so that they don't mislead.
Better still, I prefer to refactor the code so the comments are not necessary - self documenting code is better than comments because it can't get out of date.

Recently I started following more of Uncle Bob's Clean Code advices and I'm trying to transform comments into functions that enclose (extract) the commented code in a function that is at least as meaningful as the comment it replaces.

I always try to update them if I can, or at the very least add a note to the effect that they might be wrong. It's a worthwhile investment of a small amount of time.
The other thing I always do is add any relevant bug numbers, and what effect those edits had - that's always useful to see further down the line.

If the comment is necessary, I'll update it, otherwise I'll attempt to change the code to the point where I can just outright delete the comment and let the code document itself.

When i find useless GhostDoc-generated comments, i sometimes just delete them:
What's the purpose of these comments?
/// <summary>
/// Saves the form properties.
/// </summary>
/// <param name="form">The form.</param>
/// <param name="propertyNames">The property names.</param>
void SaveFormProperties(Form form, string[] propertyNames);

As a fairly fresh programmer, I don't really work much on older code as much as my own, but I try to go back every once in a while to ensure my own comments are mildly close to the truth. It makes no sense to leave comments that don't properly describe the function of the code.
That said if you're in a hurry it makes no sense to waste too much time updating comments. Adding one to the effect of "This is out of date" solves the problem of retaining navigation without leaving it ambiguous as to how accurate it is.

If your documentation is being generated from the comments (I highly recommend this anyway) then yes, I keep the comments in meticulous synch with the code.

I immediately fix the comments if I see a problem, and probably note down what it would take to improve the code.
If I then get hit by a bus, the code is all the better for my quick, pointed attention.
Then, if I have time, I'll sort the code itself out (fixing it usually requires time consuming regression testing). If not, I'll leave it for another day, but at least I'll know what the problem is right away when I do have time to come back to it.

Comments are oftten really useful for telling any future maintainers or programmers either what the code is doing or why it is doing it that way.
If you change the code without updating the comments, at best it's going to be confusing, if not downright misleading.

I strive to follow the Boy Scout Rule and leave the code cleaner than I found it. I will look to update the comment or refactor the code to obviate the need for the comment. I find that it is generally better not to have a comment at all than it is to have an incorrect comment.

I would fix the comments.
Why not fix any problem you can? If you understand the code you're working on, the comments should be the easiest fixes of all. Obviously if you've taken the trouble to delve into it the code should all be left better than you found it.
I would even posit that in groups where multiple people will be touching the code the comments could be considered just as important as the code itself. Without it the communication of ideas is broken down.
In practice I probably don't comment as well as I should. It's hard to admit that you or someone else will probably be digging around in your "masterpiece" later.

I would fix the comments. I saw some answers said they would rewrite the code if the comments were out of date. It seems absurd to me to rewrite working code just because the comments are bad. That kind behavior might even get you fired if your work is important enough.

I always fix the comments - primarily because I am usually the one who works on a piece of code. It may be an OCD like thing for me, but I just like code that I am working on to look nice - good variable names, formatting (not an issue now with modern IDE's), and comments.
I don't believe code can be "refactored to the point it is self-documenting". It can be refactored to the point where only comments for functions, procedures, member variables, classes etc. are needed, because each function call is only 1-5 lines each. Coming from a Lisp background I like to program through decomposition - much simpler, testable, and easier to prove correct.

If the project is under version control (and it should be nowadays, but you never know) and there's a huge hunk of out-of-date comments, I delete the hunk and leave a new comment to the effect that I've deleted a hunk of old comments that no longer seemed illuminating, and I submit with a note that I've deleted out-of-date comments.
Eventually, I'll remove the comment that mentions the deletion, or replace it with comments that apply to the new code.
However, here's the downside to changing old, supposedly meaningless comments in a system that's being maintained by a group of programmers:
The comments aren't acting as comments anymore! They are acting as landmarks for programmers familiar with the code. They're landmark comments as opposed to explanatory comments.
Programmers may actually be searching on keywords in landmark comments to navigate the file.
If you remove landmark comments, or even change them, you may drastically slow programmers who are using them to navigate the file. You're messing with the mental maps of people who have a long relationship with the code, and you'll do more damage than good. The brain's a funny thing. It may be much easier to remember a word or phrase in a funky comment than the name of a method.
It seems to me that if the comments are dreadfully out-of-date with the code, you should learn why. It seems incredibly presumptive to assume that the other programmers don't care about the code. Maybe they do, maybe they don't. If you're taking over the files from a guy who left, and you have clear ownership, dig in! If you're the new guy amongst a bunch of guys who've been working on the code for 20 years, and there's other evidence that they do care about the code, maybe you're missing something.
This is similar to the question of reformatting--changing spacing, altering where the opening braces go, etc. And much depends on ownership. Are you going to be in a file 20 times as much as the guy next to you? Or 1/20th as often? If it's the latter, do you really want to disorient him?
So make sure that's not what you're doing, or tomorrow you may hear someone yelling, "Where the hell is that function?"

Related

When are comments "too much", and when are they not enough? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
There is an on-going minor debate where I work about the efficacy of comments within code. One of the leads instructed his developers not to use comments as they are too "old fashioned", and a couple of other developers indicated that they never use comments because they feel all they do is clutter up the code.
I have always pretty much adhered to the practice that I comment the top of every file with a basic comment block, comment each method/class/etc definition, and then I comment any place in the code where I think I might come back in 6 months and think to myself, "WTF".
Clearly this is subjective, but I'm curious to know if anyone has any really good arguments or experiences for one way or the other.
I'll just point you to Jeff Atwood's wonderful post on the subject, which hits the nail right on the head.
In all my career, I have never come across that wonderful beast "self-documenting code". Maybe I've just been unlucky, but I'm beginning to suspect it doesn't actually exist.
Every once in a while I run across code that is so elegantly partitioned, has such compellingly obvious method, field and variable names that everything I need to know is obvious from the code.
In the general case, only really great code gurus write such code. The rest of us cobble together something that works.
If you're a really great code guru, don't bother sullying your divine code with superfluous comments.
If you barely know what you're doing, be careful to document your blundering attempts so others can try to salvage the mess.
If you're average (and most of us are, sort of by definition) then leave some hints in comments for yourself and others to make things easier at maintenance time, but don't insult anyone's intelligence and waste space by documenting the REALLY obvious. Ideally, your comments should describe your code at a meta-level, indicating not what you're doing but why. Also how, if you're doing something unusual or tricky.
"One of the leads instructed his developers not to use comments as they are too "old fashioned", and a couple of other developers indicated that they never use comments because they feel all they do is clutter up the code."
If I ever heard a developer I was working with talk like this, I would correct them. If I didn't have the necessary rank to correct them, I would leave the job.
Very clearly written code, with good identifiers -- the stuff sometimes referred to as 'self-documenting' -- does a fine job of illustrating what the code is doing. That's fine as far as it goes. The job of the comments is to explain why.
This topic tends to be discussed a lot, but here are my US$0.02 on the subject:
I would rather see too many comments than not enough. Failing at anything, you can always delete superfluous comments from the code; however, you can not derive meaning from them if there are none there to begin with.
I've heard some developers argue that other developers that "over document" (definitions of this vary by person) their code are not good developers. While saying that you are updating a counter might be a sign that you don't know what you are doing, having a clear guide to some of the business logic sitting there in the middle of the method you are working on can be quite useful.
While there are some excellent developers out there that can write extremely clear code that doesn't require comments, most developers aren't that good or they spend more time writing the code to be self documenting than they would if they had just included a couple comments.
You don't know the skill level of the next person to read your code and if the language constructs you are using might be confusing it is usually a good idea to include a comment that someone can use to Google a tutorial with.
The problem with comments is that they tend to stay long after the code that was commented has changed or even been deleted.
As a rule of thumb I'd only comment public API and difficult to understand algorithms.
Don't use comments to explain what you did - that's what the code is for, use comments to explain why you did it.
Diomidis Spinellis just wrote a nice column for IEEE column (quoted on his blog), outlining the problem, and a few solutions:
When commenting, we’re always a couple
of keystrokes away from disaster:
restating the code’s function in
English. And that’s when problems
start.
One should write comment before the code or before the function so that next time looking at the function he/she can know immediately what was the purpose of that code.
It is happened to me many times that I write the code and then forgot the purpose of that. so, I make habit of writing comment before code.
What I'd like to see in the comments is an explanation why a method that is obvious and much simpler than the method used in the code doesn't work.

Is it acceptable to have useless code?

I see that some programmers add code that, after all, does not do anything useful. For instance (C#):
[Serializable]
class Foo {
// ...
string SerializeMe() {
return new XmlSerializer(typeof(this)).Serialize(this).ToString(); // serialize to xml (syntax wrong, not important here)
}
}
The class is marked as Serializable, but the only way it is serialized is by means of XmlSerialization, which does not require that class attribute at all.
I personally hate this kind of useless code, but I see it quite often and I'm curious as to what others think about it. Is this not so serious a flaw after all? Is it common practice in the industry? Or is this just plain bad and should be removed no matter what?
Good Source Control means that useless code or code that is no longer required should be removed. It can always be retrieved from the source control at a later date.
My rule of thumb,
If its not used get rid of it.
All surplus comments, attrributes are just noise and help your code to become unreadable. If left there they encourage more surplus code in your code base. So remove it.
I try to follow the YAGNI principle, so this bothers me as well.
Does it take even a minimal effort to read that additional (useless, as you added) code?
If yes (and I think it is so) then it should not be in the code. Code like this is polluted with extra snippets that are not useful, they are there "just in case".
The "later on refactoring" of these things can be painful, after 6 o 12 months, who is going to remember if that was really used?
Really don't like it.
Because I then spend valuable time trying to figure out why it's there. Assuming that if it's there, it's there for a reason, and if I don't see the reason, then there's a chance I'm missing something important that I should understand before I start messing with the code. It irritates me when I realize that I've just wasted an hour trying to understand why, or what, some snippet of code is doing, that was just left there by some developer too lazy to go back and remove it.
Useless one-liner code can and should be removed.
Useless code that took time to write can and should be removed...but people in charge tend to get queasy about this. Perhaps the best solution is to have a ProbablyUselessButWhoKnows project where everyone can check in pointless code that might be used again in two or three years. If nothing else, this way people don't have to feel nervous about deleting it.
(Yes, in theory you can get it out of source control, but old deleted code in source control is not exactly highly discoverable.)
In a commercial project - I'd say no, especially if someone can de-assemble it for reading and then has a WTF moment.
In a home-project - sure why not, I often keep some snippets for later use.
Well I can't comment this particular piece of code without knowing your background but I personally follow strictly a rule not to have anything in code unless I really need it. Or at least know that it may be useful some day for something I have in mind already now.
This is bad code.
Bad code is common practice.
That being said sometimes it is not worth the effort in changing stuff that isn't "broken".
It would seem that perfection is attained not when no more can be added, but when no more can be removed. — Antoine de Saint-Exupéry
Is think the meaning of useless is that it cannot and will not be used. I also think that an open door is very open.
If there is an active plan to use this additional feature, then keep it in.
If you know it will never be used, or if that plan stopped being relevant 6 months ago, then pull it out. I'd comment it out first, then remove it fully later.
I'm in the midst of rescoping a lot of variables that were public but really only need to be protected or private, simply because they don't make sense from an API perspective to be exposed--that and nothing uses them.

What is your personal approach/take on commenting?

Duplicate
What are your hard rules about commenting?
A Developer I work with had some things to say about commenting that were interesting to me (see below). What is your personal approach/take on commenting?
"I don't add comments to code unless
its a simple heading or there's a
platform-bug or a necessary
work-around that isn't obvious. Code
can change and comments may become
misleading. Code should be
self-documenting in its use of
descriptive names and its logical
organization - and its solutions
should be the cleanest/simplest way
to perform a given task. If a
programmer can't tell what a program
does by only reading the code, then
he's not ready to alter it.
Commenting tends to be a crutch for
writing something complex or
non-obvious - my goal is to always
write clean and simple code."
"I think there a few camps when it
comes to commenting, the
enterprisey-type who think they're
writing an API and some grand
code-library that will be used for
generations to come, the
craftsman-like programmer that thinks
code says what it does clearer than a
comment could, and novices that write
verbose/unclear code so as to need to
leave notes to themselves as to why
they did something."
There's a tragic flaw with the "self-documenting code" theory. Yes, reading the code will tell you exactly what it is doing. However, the code is incapable of telling you what it's supposed to be doing.
I think it's safe to say that all bugs are caused when code is not doing what it's supposed to be doing :). So if we add some key comments to provide maintainers with enough information to know what a piece of code is supposed to be doing, then we have given them the ability to fix a whole lot of bugs.
That leaves us with the question of how many comments to put in. If you put in too many comments, things become tedious to maintain and the comments will inevitably be out of date with the code. If you put in too few, then they're not particularly useful.
I've found regular comments to be most useful in the following places:
1) A brief description at the top of a .h or .cpp file for a class explaining the purpose of the class. This helps give maintainers a quick overview without having to sift through all of the code.
2) A comment block before the implementation of a non-trivial function explaining the purpose of it and detailing its expected inputs, potential outputs, and any oddities to expect when calling the function. This saves future maintainers from having to decipher entire functions to figure these things out.
Other than that, I tend to comment anything that might appear confusing or odd to someone. For example: "This array is 1 based instead of 0 based because of blah blah".
Well written, well placed comments are invaluable. Bad comments are often worse than no comments. To me, lack of any comments at all indicates laziness and/or arrogance on the part of the author of the code. No matter how obvious it is to you what the code is doing or how fantastic your code is, it's a challenging task to come into a body of code cold and figure out what the heck is going on. Well done comments can make a world of difference getting someone up to speed on existing code.
I've always liked Refactoring's take on commenting:
The reason we mention comments here is that comments often are used as a deodorant. It's surprising how often you look at thickly commented code and notice that the comments are there because the code is bad.
Comments lead us to bad code that has all the rotten whiffs we've discussed in the rest of this chapter. Our first action is to remove the bad smells by refactoring. When we're finished, we often find that the comments are superfluous.
As controversial as that is, it's rings true for the code I've read. To be fair, Fowler isn't saying to never comment, but to think about the state of your code before you do.
You need documentation (in some form; not always comments) for a local understanding of the code. Code by itself tells you what it does, if you read all of it and can keep it all in mind. (More on this below.) Comments are best for informal or semiformal documentation.
Many people say comments are a code smell, replaceable by refactoring, better naming, and tests. While this is true of bad comments (which are legion), it's easy to jump to concluding it's always so, and hallelujah, no more comments. This puts all the burden of local documentation -- too much of it, I think -- on naming and tests.
Document the contract of each function and, for each type of object, what it represents and any constraints on a valid representation (technically, the abstraction function and representation invariant). Use executable, testable documentation where practical (doctests, unit tests, assertions), but also write short comments giving the gist where helpful. (Where tests take the form of examples, they're incomplete; where they're complete, precise contracts, they can be as much work to grok as the code itself.) Write top-level comments for each module and each project; these can explain conventions that keep all your other comments (and code) short. (This supports naming-as-documentation: with conventions established, and a place we can expect to find subtleties noted, we can be confident more often that the names tell all we need to know.) Longer, stylized, irritatingly redundant Javadocs have their uses, but helped generate the backlash.
(For instance, this:
Perform an n-fold frobulation.
#param n the number of times to frobulate
#param x the x-coordinate of the center of frobulation
#param y the y-coordinate of the center of frobulation
#param z the z-coordinate of the center of frobulation
could be like "Frobulate n times around the center (x,y,z)." Comments don't have to be a chore to read and write.)
I don't always do as I say here; it depends on how much I value the code and who I expect to read it. But learning how to write this way made me a better programmer even when cutting corners.
Back on the claim that we document for the sake of local understanding: what does this function do?
def is_even(n): return is_odd(n-1)
Tests if an integer is even? If is_odd() tests if an integer is odd, then yes, that works. Suppose we had this:
def is_odd(n): return is_even(n-1)
The same reasoning says this is_odd() tests if an integer is odd. Put them together, of course, and neither works, even though each works if the other does. Change it a bit and we'd have code that does work, but only for natural numbers, while still locally looking like it works for integers. In microcosm that's what understanding a codebase is like: tracing dependencies around in circles to try to reverse-engineer assumptions the author could have explained in a line or two if they'd bothered. I hate the expense of spirit thoughtless coders have put me to this way over the past couple of decades: oh, this method looks like it has the side effect of farbuttling the warpcore... always? Well, if odd crobuncles desaturate, at least; do they? Better check all the crobuncle-handling code... which will pose its own challenges to understanding. Good documentation cuts this O(n) pointer-chasing down to O(1): e.g. knowing a function's contract and the contracts of the things it explicitly uses, the function's code should make sense with no further knowledge of the system. (Here, contracts saying is_even() and is_odd() work on natural numbers would tell us that both functions need to test for n==0.)
My only real rule is that comments should explain why code is there, not what it is doing or how it is doing it. Those things can change, and if they do the comments have to be maintained. The purpose the code exists in the first place shouldn't change.
the purpose of comments is to explain the context - the reason for the code; this, the programmer cannot know from mere code inspection. For example:
strangeSingleton.MoveLeft(1.06);
badlyNamedGroup.Ignite();
who knows what the heck this is for? but with a simple comment, all is revealed:
//when under attack, sidestep and retaliate with rocket bundles
strangeSingleton.MoveLeft(1.06);
badlyNamedGroup.Ignite();
seriously, comments are for the why, not the how, unless the how is unintuitive.
While I agree that code should be self-readable, I still see a lot of value in adding extensive comment blocks for explaining design decisions. For example "I did xyz instead of the common practice of abc because of this caveot ..." with a URL to a bug report or something.
I try to look at it as: If I'm dead and gone and someone straight out of college has to fix a bug here, what are they going to need to know?
In general I see comments used to explain poorly written code. Most code can be written in a way that would make comments redundant. Having said that I find myself leaving comments in code where the semantics aren't intuitive, such as calling into an API that has strange or unexpected behavior etc...
I also generally subscribe to the self-documenting code idea, so I think your developer friend gives good advice, and I won't repeat that, but there are definitely many situations where comments are necessary.
A lot of times I think it boils down to how close the implementation is to the types of ordinary or easy abstractions that code-readers in the future are going to be comfortable with or more generally to what degree the code tells the entire story. This will result in more or fewer comments depending on the type of programming language and project.
So, for example if you were using some kind of C-style pointer arithmetic in an unsafe C# code block, you shouldn't expect C# programmers to easily switch from C# code reading (which is probably typically more declarative or at least less about lower-level pointer manipulation) to be able to understand what your unsafe code is doing.
Another example is when you need to do some work deriving or researching an algorithm or equation or something that is not going to end up in your code but will be necessary to understand if anyone needs to modify your code significantly. You should document this somewhere and having at least a reference directly in the relevant code section will help a lot.
I don't think it matters how many or how few comments your code contains. If your code contains comments, they have to maintained, just like the rest of your code.
EDIT: That sounded a bit pompous, but I think that too many people forget that even the names of the variables, or the structures we use in the code, are all simply "tags" - they only have meaning to us, because our brains see a string of characters such as customerNumber and understand that it is a customer number. And while it's true that comments lack any "enforcement" by the compiler, they aren't so far removed. They are meant to convey meaning to another person, a human programmer that is reading the text of the program.
If the code is not clear without comments, first make the code a clearer statement of intent, then only add comments as needed.
Comments have their place, but primarily for cases where the code is unavoidably subtle or complex (inherent complexity is due to the nature of the problem being solved, not due to laziness or muddled thinking on the part of the programmer).
Requiring comments and "measuring productivity" in lines-of-code can lead to junk such as:
/*****
*
* Increase the value of variable i,
* but only up to the value of variable j.
*
*****/
if (i < j) {
++i;
} else {
i = j;
}
rather than the succinct (and clear to the appropriately-skilled programmer):
i = Math.min(j, i + 1);
YMMV
The vast majority of my commnets are at the class-level and method-level, and I like to describe the higher-level view instead of just args/return value. I'm especially careful to describe any "non-linearities" in the function (limits, corner cases, etc) that could trip up the unwary.
Typically I don't comment inside a method, except to mark "FIXME" items, or very occasionally some sort of "here be monsters" gotcha that I just can't seem to clean up, but I work very hard to avoid those. As Fowler says in Refactoring, comments tend to indicate smally code.
Comments are part of code, just like functions, variables and everything else - and if changing the related functionality the comment must also be updated (just like function calls need changing if function arguments change).
In general, when programming you should do things once in one place only.
Therefore, if what code does is explained by clear naming, no comment is needed - and this is of course always the goal - it's the cleanest and simplest way.
However, if further explanation is needed, I will add a comment, prefixed with INFO, NOTE, and similar...
An INFO: comment is for general information if someone is unfamiliar with this area.
A NOTE: comment is to alert of a potential oddity, such as a strange business rule / implementation.
If I specifically don't want people touching code, I might add a WARNING: or similar prefix.
What I don't use, and am specifically opposed to, are changelog-style comments - whether inline or at the head of the file - these comments belong in the version control software, not the sourcecode!
I prefer to use "Hansel and Gretel" type comments; little notes in the code as to why I'm doing it this way, or why some other way isn't appropriate. The next person to visit this code will probably need this info, and more often than not, that person will be me.
As a contractor I know that some people maintaining my code will be unfamiliar with the advanced features of ADO.Net I am using. Where appropriate, I add a brief comment about the intent of my code and a URL to an MSDN page that explains in more detail.
I remember learning C# and reading other people's code I was often frustrated by questions like, "which of the 9 meanings of the colon character does this one mean?" If you don't know the name of the feature, how do you look it up?! (Side note: This would be a good IDE feature: I select an operator or other token in the code, right click then shows me it's language part and feature name. C# needs this, VB less so.)
As for the "I don't comment my code because it is so clear and clean" crowd, I find sometimes they overestimate how clear their very clever code is. The thought that a complex algorithm is self-explanatory to someone other than the author is wishful thinking.
And I like #17 of 26's comment (empahsis added):
... reading the code will tell you exactly
what it is doing. However, the code is
incapable of telling you what it's
supposed to be doing.
I very very rarely comment. MY theory is if you have to comment it's because you're not doing things the best way possible. Like a "work around" is the only thing I would comment. Because they often don't make sense but there is a reason you are doing it so you need to explain.
Comments are a symptom of sub-par code IMO. I'm a firm believer in self documenting code. Most of my work can be easily translated, even by a layman, because of descriptive variable names, simple form, and accurate and many methods (IOW not having methods that do 5 different things).
Comments are part of a programmers toolbox and can be used and abused alike. It's not up to you, that other programmer, or anyone really to tell you that one tool is bad overall. There are places and times for everything, including comments.
I agree with most of what's been said here though, that code should be written so clear that it is self-descriptive and thus comments aren't needed, but sometimes that conflicts with the best/optimal implementation, although that could probably be solved with an appropriately named method.
I agree with the self-documenting code theory, if I can't tell what a peice of code is doing simply by reading it then it probably needs refactoring, however there are some exceptions to this, I'll add a comment if:
I'm doing something that you don't
normally see
There are major side effects or implementation details that aren't obvious, or won't be next year
I need to remember to implement
something although I prefer an
exception in these cases.
If I'm forced to go do something else and I'm having good ideas, or a difficult time with the code, then I'll add sufficient comments to tmporarily preserve my mental state
Most of the time I find that the best comment is the function or method name I am currently coding in. All other comments (except for the reasons your friend mentioned - I agree with them) feel superfluous.
So in this instance commenting feels like overkill:
/*
* this function adds two integers
*/
int add(int x, int y)
{
// add x to y and return it
return x + y;
}
because the code is self-describing. There is no need to comment this kind of thing as the name of the function clearly indicates what it does and the return statement is pretty clear as well. You would be surprised how clear your code becomes when you break it down into tiny functions like this.
When programming in C, I'll use multi-line comments in header files to describe the API, eg parameters and return value of functions, configuration macros etc...
In source files, I'll stick to single-line comments which explain the purpose of non-self-evident pieces of code or to sub-section a function which can't be refactored to smaller ones in a sane way. Here's an example of my style of commenting in source files.
If you ever need more than a few lines of comments to explain what a given piece of code does, you should seriously consider if what you're doing can't be done in a better way...
I write comments that describe the purpose of a function or method and the results it returns in adequate detail. I don't write many inline code comments because I believe my function and variable naming to be adequate to understand what is going on.
I develop on a lot of legacy PHP systems that are absolutely terribly written. I wish the original developer would have left some type of comments in the code to describe what was going on in those systems. If you're going to write indecipherable or bad code that someone else will read eventually, you should comment it.
Also, if I am doing something a particular way that doesn't look right at first glance, but I know it is because the code in question is a workaround for a platform or something like that, then I'll comment with a WARNING comment.
Sometimes code does exactly what it needs to do, but is kind of complicated and wouldn't be immediately obvious the first time someone else looked at it. In this case, I'll add a short inline comment describing what the code is intended to do.
I also try to give methods and classes documentation headers, which is good for intellisense and auto-generated documentation. I actually have a bad habit of leaving 90% of my methods and classes undocumented. You don't have time to document things when you're in the middle of coding and everything is changing constantly. Then when you're done you don't feel like going back and finding all the new stuff and documenting it. It's probably good to go back every month or so and just write a bunch of documentation.
Here's my view (based on several years of doctoral research):
There's a huge difference between commenting functions (sort of a black box use, like JavaDocs), and commenting actual code for someone who will read the code ("internal commenting").
Most "well written" code shouldn't require much "internal commenting" because if it performs a lot then it should be broken into enough function calls. The functionality for each of these calls is then captured in the function name and in the function comments.
Now, function comments are indeed the problem, and in some ways your friend is right, that for most code there is no economical incentive for complete specifications the way that popular APIs are documented. The important thing here is to identify what are the "directives": directives are those information pieces that directly affect clients, and require some direct action (and are often unexpected). For example, X must be invoked before Y, don't call this from outside a UI thread, be aware that this has a certain side effect, etc. These are the things that are really important to capture.
Since most people never read full function documentations, and skim what they do read, you can actually increase the chances of awareness by capturing only the directives rather than the whole description.
I comment as much as needed - then, as much as I will need it a year later.
We add comments which provide the API reference documentation for all public classes / methods / properties / etc... This is well worth the effort because XML Documentation in C# has the nice effect of providing IntelliSense to users of these public APIs. .NET 4.0's code contracts will enable us to improve further on this practice.
As a general rule, we do not document internal implementations as we write code unless we are doing something non-obvious. The theory is that while we are writing new implementations, things are changing and comments are more likely than not to be wrong when the dust settles.
When we go back in to work on an existing piece of code, we add comments when we realize that it's taking some thought to figure out what in the heck is going on. This way, we wind up with comments where they are more likely to be correct (because the code is more stable) and where they are more likely to be useful (if I'm coming back to a piece of code today, it seems more likely that I might come back to it again tomorrow).
My approach:
Comments bridge the gap between context / real world and code. Therefore, each and every single line is commented, in correct English language.
I DO reject code that doesn't observe this rule in the strictest possible sense.
Usage of well formatted XML - comments is self-evident.
Sloppy commenting means sloppy code!
Here's how I wrote code:
if (hotel.isFull()) {
print("We're fully booked");
} else {
Guest guest = promptGuest();
hotel.checkIn(guest);
}
here's a few comments that I might write for that code:
// if hotel is full, refuse checkin, otherwise
// prompt the user for the guest info, and check in the guest.
If your code reads like a prose, there is no sense in writing comments that simply repeats what the code reads since the mental processing needed for reading the code and the comments would be almost equal; and if you read the comments first, you will still need to read the code as well.
On the other hand, there are situations where it is impossible or extremely difficult to make the code looks like a prose; that's where comment could patch in.

Importance of commenting your code [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 14 years ago.
How do you explain your team mates the importance of commenting the code they write? I know some coders who write episodic comments while others leave a lot to be expected, what do you expect when you read comments?
There are some minimums:
All functions and classes should be commented
Try/Catch and exception handling is better to be commented
Constants hard coded in the code should be definitely
dummy objects and dummy classes, as well as TO-DO parts should be commented
When you get a code from a URL, the address should be cited in the comments for further consideration and copyright infringement problems
Also commits to the version control system should be well commented
Although comments should be kept to minimum, there is no need to comment a for loop definition when it is obvious,
I usually set ground rules for my programmers, they stick to it when it is well defined
The best comments are always concise, in a few words. It should say what's not obvious in the code. I see allot of people making obvious and therefore useless comments like:
if x==0 //if x equals 0 then...
oh really?! This is only "polluting" the code, because unless you're learning how to program, its pretty useless.
Even if the code is only yours, you should write comments as if you were about to share it with another programmer that is completely unaware of it. That way you make sure that you will always understand it, and in long term if somebody comes along and picks that code up, that person will be able to understand it and extend/use it.
I see comments as a boost of reusability. And I expect, like every other programmer, to fully understand a block of code with a single, simple and concise comment.
Write comments when you're writing code that's not intuitive. There's really no reason for commenting a method that just iterates an array, but when you fix a bug or have to hack something together to get around an issue, it's good to have a comment so you can quickly understand that code 6 months later (and not accidently undo it).
What do you mean by commenting code?
The actual code, or the function headers?
If you're actually talking about the code, it's a lost cause. You need to get them to write readable code and to break it into meaningful chunks. Commenting bad code doesn't make it into good code, it just leaves an inconsistent mess.
As for header documentation, you have to get them to capture the important things (e.g., surprises, directives) and compromise about trivial things (listing all parameters, repeating what the signature does). People hate documenting functions because most of the effort is spent writing trivial text that almost insults your intelligence (e.g., on getHandleToFile(), "this gets a handle to the file"). Since there are actually a lot less important details than one would expect, they'd be pleasantly surprised and would be more likely to invest the effort in those specific situations.
I think if you are writing code that others may someday have to follow, then it is prudent to leave good comments about what things are doing. If you are just writing something for yourself, the tendency is strong to leave minimal or none at all. That being said, I have had the "not so luxury" of having to go back to code I wrote 8 years ago and didn't comment adequately, in a language I don't use anymore (class ASP) and I can tell you, I wish I had left more comments!
I try to comment most of my public methods and classes, and in those comments you can read what the method does, what the meaning of the parameters is, and, if applicable, what the output will be.
I also sometimes put comments inside my methods, but, there I do not comment what I'm doing, but why I am doing it like that.
if the language you are writing in is not human readable, i suggest very granular method and procedure level comments.
if the language you are writing is human readable (C#, VB, etc..) i suggest that you use somewhat detailed comments at the method level and minimal comments at the procedure level.
Include comments for document generation on methods and classes.
Don't comment every line.
If you are doing something expected or that is not obvious from the code, explain why in comments.
The most important thing to do in commenting is to tell the truth. The number of times I've been investigating a bug only to find a section of code that is "less than obvious" along with a comment that says it's supposed to do the opposite to what it is doing. Who wins? You decide...
On a related note, any comment that is longer than the section it is documenting is normally too long.

Commenting code that is removed [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Closed 5 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Is it a good practice to comment code that is removed? For example:
// Code to do {task} was removed by Ajahn on 10/10/08 because {reason}.
Someone in my developer group during a peer review made a note that we should comment the lines of code to be removed. I thought this was a terrible suggestion, since it clutters the code with useless comments. Which one of us is right?
Generally, code that is removed should not be commented, precisely because it clutters the codebase (and, why would one comment on something that doesn't exist?).
Your defect tracking system or source control management tools are where such comments belong.
There are some (rare) situations when commenting code out (instead of deleting) is a good idea. Here's one.
I had a line of code that seemed good and necessary. Later I realized that it is unnecessary and harmful. Instead of deleting the line, I commented it out, adding another comment: "The line below is wrong for such and such reason". Why?
Because I am sure next reader of the code will first think that not having this line is an error and will try to add it back. (Even if the reader is me two years from now.) I don't expect him to consult source control first. I need to add comment to warn him of this tricky situation; and having wrong line and the reason why it is wrong happened to be the best way to do so.
I agree that it is not a good idea to leave code removed in comments.
Code history should be viewed through a version control system, which is where old code can be found, as well as the reason it was removed.
You should delete the code always.
As for being able to see old/removed code, that's what revision control is.
Depends on the reason for removal.
I think of comments as hints for people maintaining the code in the future, if the information that the code was there but was removed can be helpful to someone maintaining the code (maybe as a "don't do that" sign) then it should be there.
Otherwise adding detailed comments with names and dates on every code change just make the whole thing unreadable.
I think it's pretty useless and make the code less readable. Just think what it will be like after some monthes....
// removed because of this and that
/*
removed this stuff because my left leg...
*/
doSomething();
// this piece of has been removed, we don't need it...
You'll spend half an hour to find out what's going on
The question is, why do you remove code?
Is it useless? Was it a mistake to put it there in the first place?
No comments needed from my point of view.
It's useful when debugging, but there's no reason to check in code that way. The whole point of source control is being able to recover old versions without cluttering up the code with commented-out code.
I would suggest that, yes it's good practice to comment on code that has been removed but not in the code itself.
To further clarify this position, you should be using a source code control system (SCCS) that allows some form of check-in comment. That is where you should place the comments about why code was removed. The SCCS will provide the full contextual history of what has happened to the code, including what has been removed. By adding check-in comments you further clarify that history.
Adding comments in the code directly simply leads to clutter.
The recent consensus (from other discussions on here) is that the code should just be removed.
I personally will comment out code and tag it with a date or a reason. If it's old/stale and I'm passing through the file, then I strip it out. Version control makes going back easy, but not as easy as uncommenting...
It sounds like you are trying to get around versioning your code. In theory, it sounds like a great idea, but in practice it can get very confusing very quickly.
I highly recommend commenting code out for debugging or running other tests, but after the final decision has been made remove it from the file completely!
Get a good versioning system in place and I think you'll find that the practice of commenting out changes is messy.
Nobody here has written much about why you shouldn't leave commented-out code, other than that it looks messy. I think the biggest reason is that the code is likely to stop working. Nobody's compiling it. Nobody's running it through unit tests. When people refactor the rest of the code, they're not refactoring it. So pretty soon, it's going to become useless. Or worse than useless -- someone might uncomment it, blindly trusting that it works.
There are times when I'll comment out code, if we're still doing heavy design/development on a project. At this stage, I'm usually trying out several different designs, looking for the right approach. And sometimes the right approach is one I had already attempted earlier. So it's nice if that code isn't lost in the depths of source control. But once the design has been settled, I'll get rid of the old code.
In general I tend to comment very sparsely. I believe good code should be easy to read without much commenting.
I also version my code. I suppose I could do diffs over the last twenty checkins to see if a particular line has changed for a particular reason. But that would be a huge waste of my time for most changes.
So I try comment my code smartly. If some code is being deleted for a fairly obvious reason, I won't bother to comment the deletion. But if a piece of code is being deleted for a subtle reason (for example it performed a function that is now being handled by a different thread) I will comment-out or delete the code and add a banner comment why:
// this is now handled by the heartbeat thread
// m_data.resort(m_ascending);
Or:
// don't re-sort here, as it is now handled by the heartbeat thread
Just last month, I encountered a piece of code that I had changed a year ago to fix a particular issue, but didn't add a comment explaining why. Here is the original code:
cutoff = m_previous_cutofftime;
And here is the code as it was initially fixed to use a correct cutoff time when resuming an interrupted state:
cutoff = (!ok_during) ? m_previous_cutofftime : 0;
Of course another unrelated issue came up, which happened to touch the same line of code, in this case reverting it back to its original state. So the new issue was now fixed, but the old issue suddenly became rebroken. D'oh!
So now the checked-in code looks like this:
// this works for overlong events but not resuming
// cutoff = m_previous_cutofftime;
// this works for resuming but not overlong events
// cutoff = (!ok_during) ? m_previous_cutofftime : 0;
// this works for both
cutoff = (!resuming || !ok_during) ? m_previous_cutofftime : 0;
Of course, YMMV.
As the lone dissenting voice, I will say that there is a place for commenting out code in special circumstances. Sometimes, you'll have data that continues to exist that was run through that old code and the clearest thing to do is to leave that old code in with source. In such a case I'd probably leave little note indicating why the old code was simply commented out. Any programmers coming along after would be able to understand the still extant data, without having to psychically detect the need to check old versions.
Usually though, I find commented out code completely odious and I often delete it when I come across it.
If you are removing code. You should not comment it that you removed it. This is the entire purpose of source control (You are using source control? Right?), and as you state the comment just clutters up the code.
I agree that it's a terrible suggestion. That's why you have Source Control that has revisions. If you need to go back and see what was changed between two revisions, diff the two revisions.
I hate seeing code that's cluttered with commented out code. Delete the code and write a commit message that says why it was removed. You do use source control, don't you?
Don't litter active code with dead code.
I'll add my voice to the consensus: put the comments on why code was deleted in the source control repository, not in the code.
This is one of those "broken" windows thinkgs like compiler hints/warnings left unaddressed. it will hurt you one day and it promotes sloppiness in the team.
The check in comment in version control can track what/why this code was removed - if the developer didnt leave a note, track them down and throttle them.
A little anecdote, for fun: I was in a company, some years ago, knowing nothing of source code version control (they got such tool later...).
So they had a rule, in our C sources: "when you make a change, disable the old code with preprocessor macros":
#ifdef OLD /* PL - 11/10/1989 */
void Buggy()
{
// ...
}
#else
void Good()
{
// ...
}
#end
No need to say, our sources quickly became unreadable! It was a nightmare to maintain...
That's why I added to SciTE the capacity to jump between nested #ifdef / #else / #end and such... It can be still useful in more regular cases.
Later, I wrote a Visual Studio macro to happily get rid of old code, once we got our VCS!
Now, like buti-oxa, sometime I felt the need to indicate why I removed some code. For the same reason, or because I remove old code which I feel is no longer needed, but I am not too sure (legacy, legacy...). Obviously not in all cases!
I don't leave such comment, actually, but I can understand the need.
At worse, I would comment out in one version, and remove everything in the next version...
At my current work, for important local changes, we leave the old code but can reactivate it by properties, in case of emergency. After testing it some time in production, we eventually remove the old code.
Of course, VCS comments are the best option, but when the change is a few lines in a big file with other changes, referencing the little removal can be hard...
If you are in the middle of major changes, and need to make a fix to existing functionality, commenting out the future code is a reasonable thing to do, provided you remark that this is future functionality, at least until we have futures friendly source control systems.
I comment unnused code because you never know when will you have to fallback on the ancient code, and maybe the old code will help other people to understand it, if it was simpler back then.
I agree with you Andrew; IMO this is why you use version control. With good checkin/commit comments and a diff tool you can always find out why lines were removed.
If you are using any form of Source Control then this approach is somewhat redundant (as long as descriptive log messages are used)
I also think it's a terrible suggestion :)
You should use source control and if you remove some code you can add a comment when you commit. So you still have the code history if you want...
There's a general "clean code" practice that says that one should never keep removed code around as commented out since it clutters and since your CVS/SVN would archive it anyway.
While I do agree with the principle I do not think that it is an acceptable approach for all development situations. In my experience very few people keep track of all the changes in the code and every check-in. as a result, if there is no commented out code, they may never be aware that it has ever existed.
Commenting code out like that could be a way of offering a general warning that it is about to be removed, but of course, there are no guarantees that interested parties would ever see that warning (though if they frequently work with that file, they will see it).
I personally believe that the correct approach is to factor that code out to another private method, and then contact relevant stakeholders and notify them of the pending removal before actually getting rid of the function.
Where I am at we comment out old code for one release cycle and then remove the comments after that. (It gives us quick fix ability if some of the new code is problematic and needs to be replaced with the old code.)
In almost all cases old code should of course be removed and tracked in your RCS.
Like all things though, I think that making the statement 'All deleted code will ALWAYS be removed' is an incorrect approach.
The old code might want to be left in for a miriad of reasons. The prime reason to leave the code in is when you want any developer who is working in that section of code in the future to see the old code.
Relying on source tracking obviously does not give this.
So, I believe the correct answer is:
-Delete old code unless leaving it in provides crucial information that the next developer in the code would require. Ie, remove it 99% of the time but don't make a draconian rule that would remove your ability to provide much needed documentation to the next developer when circumstances warrant it.

Resources