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

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.

Related

Is commenting every right brace good/bad style? [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
I am teaching an upper-division software engineering course and am reviewing every student's code. Some of my students have picked up the habit elsewhere of adding a comment to the right of every closing brace identifying the statement type, such as:
if (x > 3) {
y = 10;
} //if
I have told the students to follow the Android code style guidelines, which says nothing about this practice. On what grounds should I tell them not to do this (besides personally not liking it), or should I permit it?
Comments are for clarifying code and increasing readability. It's clear enough to most reasonable software developers that the statement is an "if." Furthermore, many IDEs and editors automatically highlight brackets such as these, so the comment isn't necessary. Generally, you should save comments for describing what methods, classes and variables do (e.g. in Javadoc), or what subroutines within a method will do. This is based on the general guideline of making sure everything you add improves the code.
Tell them that they should assume that person who review code knows language syntax and how to program. Comments should be rare, indicate and explain some weird and not obvious code section (for instance the api provided by some library is bugged and some workarounds/hacks are needed). We've got documentation (and unit tests) to explain how to use and how code should behave. For educational purpose you can write small class/module filled with such "comment-documentation", give it to students and ask them what did they learn about code from these comments.
Well, most likely this will end up in a discussion based on personal preference - which is not within the scope of stackoverflow. But aI'll answer anyway:
In my opinion, that's a bad thing to do - for multiple reasons.
It messes up the code. the more comments are in there, the less readable it is. A single } in a line tells me, instantly, that the last block ends here. with the comment behind, there is more to read - and no additional info (but people will read anyway, cause they don't know that the comment doesn't include any info... and because people tend to read everything automatically)
It leads to sloppy indentation. After all, that may even be the reasons people started that in the first place.
it's unnecessary - if I indet the code in a consistent manner, it shouldn't be necessary to note what was closed, it should be easily visible by just going up to where the last statement with the same indentation level was. In most cases (unbless you're reverse-indenting (or whatever that is called), which I don't like at all) this should be very easy, as there is nothing in between...
it leads to bigger file sizes. may be invalid on modern systems, but still.
Every time is overkill. It depends on the level of indentation and the length of your function, but these are usually signs that you need to step back and refactor. The only time I explicitly do it is for namespaces in C++

What are examples of comments that tell you WHY instead of HOW or WHAT?

First of all, in this question I'd like to stay away from the polemic on whether source code commenting is good or bad. I'm just trying to understand more clearly what people mean when they talk about comments that tell you WHY, WHAT or HOW.
We often see guidelines like "Comments should tell you WHY; code itself should tell you HOW". It is easy to agree with the statement on an abstract level. However, people usually drop this like a dogma, and leave the room without further explanation. I've seen this used in so many different places and contexts, that it looks like people can agree on the catchphrase, but they seem to be talking about different things entirely.
So, back to the question: if comments should tell you WHY, what is this WHY we are talking about? Is this the reason why that piece of code exists in the first place? Is this what that piece code should be doing? I would really appreciate if someone could give a clear explanation, and then add some good examples (bad examples are not really needed, but fell free to add them for contrast).
Please do not immediately close this question as duplicate or polemic. I have tried hard to make it very objective. There are many questions on whether comments are good or bad, but no one that addresses the specific question of what are good examples of comments that tell you WHY.
Thanks,
Comments serve two main purposes:
to summarise. Many would say "why document this method when we can just read the code?", but one line of text that describes what a method is for/what it does, can often be much faster to read and easier to understand than 30 lines of code, especially if that code calls other methods that you may need to read as well...
to explain the things that are not obvious from the code - the WHY, or more detail on the how. Simple examples include "we must add the new XmlElement and then remove the old one, as the ReplaceChild method in .net does not work!", or "Uses an iterative Newton-Raphson approach to solve for X ", or "we must not close the port here because the reading thread may still be running", or "use this method where performance is critical, but beware that this method may provide a result that is in error by up to 5%"

How to Make Program Comments More Useful?

Hai guys,
I ve seen people including comments in their program..
Is it to improve inter-programmer communication
and code readability, by explicitly specifying programmers’
intentions and assumptions?
Should comments be in technical terms rather than in natural launguage terms?
How to use comments as effective as possible?
Is it really a good practice adding comments to a program?
Comments should only be used to explain why the code is the way it is. It should never explain what the code is doing. What the code is doing is described by the code.
That being said, some languages have tools that look for special characters in the comments in order to generate documentation. Java is one such language. But these aren't so much code comments as they are documentation that happens to use the same syntax as language comments.
Comments can be used for auto-documentation, communication amongst other developers, memory, todo lists, or basic explanations of functionality. Note that comments ought to be supplementary - if your code needs comments, you need to reconsider your code.
To be as effective as possible, work out a template for your comments to exist in. Again, this will not only help you read and understand your code, but it may help a parser create documentation for you from your comments if they're in a consistent format throughout the code.
Writing clear code is always the first step to making your code easy to understand. You can then explain parts that are not clear by looking at the code, in comments.
For myself, comments explain what I was thinking at the time. That way, six months from now when I don't remember what I was writing, I can use the comments to understand.
Some classic uses of comments:
Explaining why code wasn't done in the most obvious way -- Such as interfacing with systems that use weird or old ways to talk.
Explaining what code might call this code -- Such as in large and complicated system. You can add examples showing code that might need to call this.
Documenting exceptions to current coding practice -- Such as legacy code that hasn't been refactored to use the current systems.
As a rule, if you ever find yourself doing something non-obvious, comment it.
An alternative way of commenting is to start by writing the body of a function as comments. Then break the comments apart and put the code underneath. When it finally works, cleanup and fix the comments.
Ciao!
I try and comment each function describing at a high level, but precise way, what the function does. The precision should be such that it is not necessary to read the body of the function to understand what the function does, or to re-implement it and have it work perfectly with any code that calls it.
Other than that, I try and keep functions small enough that the above is basically all the necessary documentation.
Once in a while, there may be something obscure or odd in what is being done in the code - I document that. Anything that isn't obvious or intuitively right, or that you spent some time thinking about, should be documented.
Just imagine you have a memory problem and will forget writing this program in a month. Then imagine you have to go back and fix it. What would you like commented and how could those comments be made most useful to you?
it's better to make the program self-describing, then no much comments are needed.
First try to write code so people can follow without comments.

Do you update ancient code comments that are wrong? [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 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?"

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.

Resources