Comments are More Important than Code 1021
CowboyRobot writes "I was going through some code from 2002, frustrated at the lack of comments, cursing the moron who put this spaghetti together, only to realize later that I was the moron who had written it.
An essay titled Comments Are More Important Than Code goes through the arguments that seem obvious only in hindsight - that 'self-documenting' code is good but not enough, that we should be able to write code based on good documentation, not the other way around, and that the thing that separates human-written code from computer-generated code is that our stuff is readable to future programmers.
But I go through this argument with my colleagues, who say that using short, descriptive variable names 'should' be enough as long as the code is well-organized.
Who's right?"
Re:Gotta document that code... (Score:5, Insightful)
Comment. (Score:3, Insightful)
Something i notice (Score:5, Insightful)
but just putting a bunch of blocks of comments that are like "get customer", "build record", etc are basically useless. If you use programming by intent then its more or less obvious that the code
GetCustomerFromDatabase(foo)
is going to do something with a database and get a customer. a comment telling me that is useless.
what i like to do is write a few paragraphs of text at the top of a function. it explains my general approach, why im doing certain things the way i am, why im not doing other things, and why the function even exists.
essentially the comments should be enough that anyone that knew the problem space ought to be able to read them and come up with more or less a similar implementation.
then, in the body of the method anytime i do something that i feel isn't completely obvious, i put a 1 or 2 liner infront of, i.e. "we have to do this because zergs are sensitive"
the end result of all of this is that code reviews can see what you were thinking at the time the code was written.. and you're documenting assumptions about the problem, the apis, your understanding of the language, etc, all right in the code. it makes finding errors pretty easy.. someone that can't even read source code can read the comments and get an idea of the correctness of your approach.
Re:Gotta document that code... (Score:5, Insightful)
On that topic, what are some good examples of well-commented code? Rather than just see words, I'd rather see real-life applications of these practices. For starters, here's typically how much I comment my code: Allacrost source code [sourceforge.net] (note: not all files were written by me, by I try to stress heavy commenting on the rest of my team)
Re:Even more annoying... (Score:5, Insightful)
What are programming languages for? (Score:2, Insightful)
If it turns out that after all that, our code still isn't intelligible, then isn't this some monumental failure of C, Java, BASIC and the rest, whose whole raison d'etre is to make weird things make sense?
New Techniques and Better Programmers. (Score:5, Insightful)
If the comments are clear, a better programmer than you can come along later and say "What the hell was this guy doing?" and then replace your lines of fumbling crap with much cleaner/clearer code.
It's the difference between being able to see what you were trying to do vs. figuring out what you actually did.
Call it "Intent Oriented Programming" if you want.
They are (Score:4, Insightful)
Comments are a maintenence nightmare. They get out of sync with the code, and (especially when the code is bad to begin with) people read them instead of the code.
That means over time the human's understanding of what the program does starts to diverge from the computer's understanding.
This is not good.
If something is too hard to understand the way it is written without comments, it should be rewritten. You will save time in the long run, trust me.
Remember the old adage: Don't get suckered in by the comments--the bug is in the code.
--MarkusQ
Re:And this, my friends, is why offshore outsourci (Score:3, Insightful)
I disagree. India has more engineers than the USA. And these are smart people. Some of them already know english, and others will have to learn. India is a country with too much poverty and so little oppertunity, that when a young kid is given a chance, he'll learn it all. They are lean (paid little) and hungry (willing to learn). In the USA, we expect $100 an hour to consult, one place I worked at hired an Arthur Anderson consulting team and the lead got over $300 an hour. I bet he would be *insulted* to have to work for $20 an hour. Are you going to tell me that the guy in India won't take that wage?
If it means people in India will have to learn english, they will learn english the same way they get their engineering degrees. They will study their asses off like their lives depend on it.
If people in the USA have half a chance, now is the time to take advantage of it and produce a better product than they do in India. Leverege every advantage we have, because the competition is getting better.
We could say how the Bush administration is screwing us, and to a large extent they are. We never should have let factories leave the USA to mexico. We never should have let outsourcing happen. I hope future presidents start raising the tariff, and force American companies back in the USA. But maybe we need to get a little more lean. It is hard for the avarage employee to give a fuck when you see the CEO get a bonus when he lays people off, or scum like enron managment steal the pensions of employees, but what other option do we have? Change the tax code to tax the wealthiest at a higher rate and pump that money back to the poor? Maybe raise the luxery tax rate? Increase the estate tax? Break monopolies?
The problem isn't lack of comments (Score:5, Insightful)
Re:No such thing as too many comments... (Score:2, Insightful)
if (kbd_input_rcvd)
{
process_input();
}
is not clear?
I think properly modularizing your code (breaking process_input() into its own function), and properly documenting the modules (defining good documentation of input, output, exception conditions, return values, side-effects) is more effective than writing verbose comments (like the one you've noted) in poorly segmented code.
This whole discussion is a bit short sighted. The better and clearer your code is, the fewer comments will be necessary. The more useful comments you add, the less time will be necessary parsing and understanding clear code. The better your design overall is, the less code reading overall will be required, because you'll have documentation outside of your code that explains how the system works, and where you need to go make changes. Saying one is more important than another is silly.
Re:Even more annoying... (Score:2, Insightful)
Re:Gotta document that code... (Score:2, Insightful)
I actually agree with you though -- as long as the indent character in question is a tab. People who want to indent with spaces need their heads examined.
Re:Gotta document that code... (Score:3, Insightful)
It's annoying when I go to the person who wrote a chunk of code fom a couple months ago to ask them some questions, they look at the code and have no idea why they were doing what they were doing.
I've always followed the philosphy that I should write and comment code so that someone who wasn't a programmer could read it and understand what was going on. This makes it very easy to go back even years and know exactly what the code was doing and why it was doing it.
But you need to write good comments and good code. I've actually seen this in code:
Gets an array.
@return An array.
*/
Array GetArray()
The other one I live seeing is data structures containing non-descriptive field names:
struct TmpData
{
int a;
int b;
float c;
};
Completely useless.
Good code and good comments makes everyone's life easier. I've seen a lot of good code, I'd like to see a lot more good comments as well.
~X~
Re:Gotta document that code... (Score:5, Insightful)
Hello. I question. Look, if you need comments to explain the code flow because your method spans four screens and has six levels of conditionals in two levels of loops, all the comments in the world won't help you.
Especially if you change the code and now the comments are wrong
I have had the joy of maintaining lovingly commented code with all these huge blocks at the start showing what args get passed and what happens, and I can't understand a god damned thing about what it's doing, because the code all looks like All generalisms are wrong.
Re:development process (Score:3, Insightful)
Re:Use long variable names (Score:5, Insightful)
Now with that out of the way, here's my philosophy on variable names... Every variable name should be as long as necessary to describe what the variable is. Having said that, the shorter, the better. If you have a lot of long variable names, then you probably have not found the most elegant solution to your problem.
Re:Even more annoying... (Score:5, Insightful)
You know whose fault that is? The morons that mark you down if you don't comment trivial programs like Hello World.
I actually ended up doing three introductory programming courses at college and university (overlap in curricula), and I've been marked down for not including this type of comment in all three courses.
The problem is that they try and teach you to write comments prematurely. When all most people on the course can write are programs like Hello World, they really can't see the use of comments and there are no good examples to give. The use of comments should come after things like functions etc IMHO, so that students can actually see how comments can be useful.
Debug code not comments (Score:5, Insightful)
For example which would you rather read.
#define AgentNameLen 41
#define CustomerNameLen 51
struct CustomerID
{
int CustomerID;
char AgentName[AgentNameLen];
char CustomerName[CustomerNameLen];
};
or
struct CoID
{
int ID;
char AName[41];
char CName[51];
};
To me the first is much more clear, and throughout the code will be obvious as to it's use. The second is mildly clear, but will degrade as new things get added to the structure.
The first also allows things like
for(int i=0;iAgentNameLen;i++)
which makes it very clear that you are iterating throught the agent name.
Algorithm's should be documented, as much as possible, at the top of the function, and any function that takes more then a screen should be looked at to see if it can be broken up into smaller functions.
(Almost) Always code towards maintainability, never speed. Usually it pays off within the year.
So to sum up. In order of importance:
80% code clearly with an eye towards maintainablity
20% comment
Re:Gotta document that code... (Score:5, Insightful)
Actually I have found that more often than not, not documenting properly only bites someone else in the ass.
This is likely the source of the problem, and the least likely to change. I suppose it could be part of the QA process to check for notation on code, but I somehow suspect that with programming jobs on a one way trip to Bangalore that readability it secondary to "works cheap."
~Rebecca
Re:Gotta document that code... (Score:3, Insightful)
So I don't question. The story poster is correct. Code needs to be well documented, and neither good organization nor descriptive variable names is a sufficient replacement for documentation. But you're absolutely correct too that documentation is only a small part of what it takes to write good code.
Re:Gotta document that code... (Score:3, Insightful)
The corollary to this is the need to maintain existing comments when the code is changed. Misleading/outdated comments can sometimes be worse than none at all.
proper documentation is professional courtesy
I couldn't agree more. Good documentation gives you context and insight into the motivation of a past developer, which can be priceless when trying to understand unfamiliar code. Good variable names can give you the "how" the code is implemented, but good comments give you the "why".
Re:And this, my friends, is why offshore outsourci (Score:1, Insightful)
Most indian graduates already know english, if not almost all of them!?
I guess it makes us feel safer if we come up with more reasons for another culture's inferiority?
PS: I am not indian..
Re:Nah (Score:5, Insightful)
Blockquoth the AC:
That was modded (+1, Funny), but I think it was a serious comment. It wasn't a bad rule of thumb, either.
The What, the Why, and the How (Score:3, Insightful)
The What: What is this code trying to do. This is where your design documents come in, as they tell what the overall goal of the program is.
The Why: Why are you doing what you are doing? Why are you writing to this hardware register twice? Why do you divide this value by 1800 here? This is where comments are needed - to explain that the hardware sometimes doesn't take the value on the read, or that the nominal deviation of this signal is 1800 Hz.
The How: How are you getting the work done. This is where well written code with well chosen variable names comes in.
The only thing worse is old comments (Score:2, Insightful)
People will usually update variable names, but they won't update comments, especially when the IDE makes comments a different colour - your eyes don't even see them after a while.
You think spaghetti code is bad with no comments - try it with misleading comments.
Re:Write code like someone else will maintain it (Score:3, Insightful)
People sometimes forget that you are not only documenting WHAT the code is doing, but WHY you are doing it that way. You can usually figure out the what from the code itself, but trying to figure out the why can be next to impossible.
I wrote some code years ago to calculate (Australian) Capital Gains Tax liabilities. I knew it would be a hassle to update the code when the tax laws were inevitably reviewed and updated, so I went out of my way to put notes about EVERYTHING into the source code. Where I would normally have put in a short quip, I put in a longer descriptive comment.
Five years later when changes had to go in, it took me an hour or two to get back up to speed with how the program worked, but without that extra documentation it would have taken far longer and I would more likely have broken it when trying to patch it.
What do you guys think of the following code? (Score:5, Insightful)
I kid you not, this is real code my supervisor writes.
Note that this is matlab code, where commas are both an end-of-statement indicator (it's also possible to use just a semicolon), and an array index separator. The nice thing about this code, is that I can at least guess where most of the variable names come from. Oh, and there was *no* line break in the original code. Hooray for the avoidance of those wasteful '/n' characters?!?!
To answer the original poster: yes, comments are of vital importance.
Then again, if a program is structured right, things can be organized into sections, each of which is then commented, as opposed to a bunch of seemingly random lines with comments spaced throughout. Sometimes the layout of code, in conjunction with good variable names, is the best possible method of commenting it. The one thing comments are good for is to assure that someone not familiar with the particular language being used, will still understand the purpose of the code.
Hmmm... (Score:3, Insightful)
Re:Even more annoying... (Score:3, Insightful)
You need both (Score:2, Insightful)
Re:Gotta document that code... (Score:5, Insightful)
There's no solution to the indention problem. You'd think simply mandating tabs would work, because that way everyone can set the tabstops to whatever they want, but in practice it doesn't work. People don't setup their editors the same way. Some have "tab indents with tab", which would be the correct choice, but other have "tab indents with spaces". Then you have those that refuse to use tab at all, or decide to use spaces to align certain blocks, and so you get a mix of tabs and spaces in a line. The line looks right with tabstop=4, but looks like crap with the default tabstop of 8. This assumes people don't untabify on open and save. That replaces all tab characters with spaces.
In practice, a file that is touched by enough people will end up having every line indented to some screwy level with nothing lining up correctly. I know. I've seen it.
Re:New Techniques and Better Programmers. (Score:3, Insightful)
Tests are more important than comments. (Score:3, Insightful)
The problem with comments is there is no constraint to keep them...
Code Reviews help, but not enough.
There is a better way. It is called Test Driven Development. Tests are the least ambiguous, most correct and current commentary on the code. They are also always at the correct (higher) semantic level than just paraphrasing the code.
Given a choice of reading comments or reading well structured tests, I will read tests any day. I at least know if they run, that they are true.
Google knows. [google.com]
Re:Gotta document that code... (Score:5, Insightful)
speak for yourself. I know my 4-space indents will be the same regardless of whatever editor and/or settings are used. and I won't get warnings about the tab character from my f90 compiler.
Re:Gotta document that code... (Score:3, Insightful)
That's not true. One line comments won't help, but a large descriptive comments will. If you can explain the code by talking about it, then you can explain the code by writing about it.
Especially if you change the code and now the comments are wrong
You're incompetent if you don't change the comments to match the code. You're equally incompetent if you come across incorrect comments and leave them in. You're supposed to the job, so do it.
I have had the joy of maintaining lovingly commented code with all these huge blocks at the start showing what args get passed and what happens, and I can't understand a god damned thing about what it's doing, because the code all looks like
As Fred Brooks said, "There is no silver bullet." Clearly written code can't replace comments. Clearly written comments can't replace poorly written code.
Re:The problem isn't lack of comments (Score:3, Insightful)
http://en.wikipedia.org/wiki/Orthogonal_functions
I'll reply again in a couple weeks after I've figured out if my functions are orthogonal or not.
Top Ten Code Comment Do's List (Score:5, Insightful)
- Function name
- what it does
- parameters
parameter name - what is is for and any restrictions on it (i.e., must not be null)
- return value (all possible return values)
2. Add comments to each file you modify so that over time, the file becomes better documented
3. Add ASSERT() like comments and ASSERT() or equivalent to your code
4. Use dividing comments like a line of dashes to seperate blocks of code
5. Put in a '?' comment for code that you do not understand (good for function headers)
6. Avoid stupid naming schemes for your local variables since that makes it harder to comment
7. Review your code for both logic and comment completeness after you code it before committing it to version control
8. Tag your bug fixes, code enhancements with a comment followed by a dash, date, and your initials. This is essential for large projects or for anything you will be working on for more than 6 months.
9. Format your comments so that multiple line comments line up on the left hand side (increases readability)
10. Don't count on java doc or equivalent as being good enough code documentation.
Re:The problem isn't lack of comments (Score:3, Insightful)
I find these rules very helpful. Secondly, many times your code evolves and changes, and it's important that you continuously re-examine your functions too see if there are newly created logical dividing points.
Re:Even more annoying... (Score:5, Insightful)
Write 5 lines. Write 20 lines. Write 100 lines. Of useless and pointless code.
What should be done is: Take this 1000 line programme. Add on 5 lines. Add on 20 lines. Add on 100 lines. Beacuse that would require being able to read code, too. Being able to understand what is already there is frequently more then half the battle. Saying "What the fuck does this mean?" a few dozen times is the only way to get to write comments. Being a sysadmin, rather then a full time programmer, this took me litteraly years to learn. And it was usualy "What the fuck were you doing here, brain? Dammit, one of these days were going to have to start commenting our code."
About 6 months ago, I read through a project request on one of these ebay-for-coders sites. Language optional; 1 comment per 5 LOC, but if using Perl, 1 comment per 2 LOC.. With requrements like that you are only asking to get BS comments like "Print X to the console".
Re:Gotta document that code... (Score:5, Insightful)
There's also something as far as too much commenting. Don't get me wrong, I can't stand uncommented code. I learnt, like most people, the hard way -- go back to edit something I did 6 months ago, and have no idea what's happening.
But I don't think this is useful:
Here's my version of your same section This isn't really the greatest example, but I like to comment sections of code. The details can be read by looking through the code, with "hints" as needed (for example, reminding me that SDL_GetTicks() is the current time).
Well commented blocks mean you can skim through the code, getting a quick overview of what's happening, without having to read in much detail. You don't have to care about the details of the look, you just know by the time you hit the } you've found what you wanted.
Don't take this personally or anything. Your code is very readable.. there's just lots of extra comments (granted, I've seen worse) that are really just not worth putting in.
(also, proper indenting is as, if not more, important.. of course,
Re:Even more annoying... (Score:5, Insightful)
No, the problem is that they try and teach you to write code prematurely.
Document your application, requirements, constraints, and system interactions (what the engineer does). Then write the code (what the coder does).
What you will quickly learn is that it's better to be the engineer than the coder. What you'll realize is that the engineer is the client-side guy that figures out how to solve the challenge presented and the coder is the guy who can live in Manipal.
The computer scientist is another guy altogether, that sets the boundaries within which the engineer must work and provides many of the tools.
Somehow CS education has gotten horribly derailed, and asks students to combine the equivalents of electromagnetic theory, power system design, and basic home wiring in one curriculum. No wonder enrollments are plummeting - nobody knows what a CS major is or should do.
You new fangled whipper snappers (Score:3, Insightful)
Re:Use long variable names (Score:3, Insightful)
Re:Even more annoying... (Score:1, Insightful)
I'm a CS grad student, and the stuff I see from my fellow grad students amazes me. A pretty large percentage of our incoming students are from India, and it's obvious that a lot of them have never written any significant amount of code. (From talking to a few of them, I get the distinct impression that the indian educational system is pretty much memorize-and-regurgitate all the way up).
In one case one of my fellow grad students was working on a fairly trivial assignment - Take the results of a web form and email them somewhere. (Yeah, in a grad level class. What a joke.). This was done in Perl, and he was having trouble getting it working. So he asked me to look at his code.
No indentation. Sometimes two or three statements on a line. Random line spacing. No Comments. No use strict. No use warnings. No variable declarations whatsoever. Variable names like $a, $b, etc. Moreover, he'd turned what is about a 10 line Perl script into a good solid 50+ lines of code. Augh!!
Re:The problem isn't lack of comments (Score:1, Insightful)
Necessary on low-level code and interfaces (Score:2, Insightful)
In assembly, this is totally necessary. For example, this old DOS code
Obviously, without the comments, you won't understand what I wanted to do, and you could for example suppose that I could have replaced 'mov bl,7' by 'mov bl,ah' since they were identical, which was pure coincidence.
In higher level code, on tree-walking functions, or in finite state machines, you need to comment your intent, because you'll always put bugs, and the only thing which counts is the algorithm that you validated by hand on paper. So you explain what you tried to do, and anybody reading your code (including you) will then understand why some transitions don't work as expected.
I often ask friends to comment their interfaces so that even themselves know if their input is valid. Example below:
But on the other end, I hate useless comments such as all cited in other posts (eg: print "x" on console). They make it difficult to read code.
Following such rules will generally help people understand your code, and help yourself maintaining it over the years. That's also one reason I quickly forgotten how to code in perl
Willy
Re:Top Ten Code Comment Do's List (Score:2, Insightful)
* Possible return values: [2 - 4999]
hehehe..
Re:Tests are more important than comments. (Score:3, Insightful)
Uhhh, no. That's when the massive body of unit tests saves your bacon. You had to make a change that caused the tests to start failing. Once the tests are all running again, your system has at least the level of quality it had before you made your changes.
You and your team do have to follow a rule of not deleting possibly relevant tests. Ever.
Those tests don't do you jack if all they do is tell you there's a bug.
Sounds like you haven't written many unit/functional tests. The way it works is: you write tests for small pieces (A, B, and C) and then you write the tests for the part of the system that uses those small pieces (ABC).
If the test for B and the test for ABC are failing, pray tell... where's the problem?
What's worse than commented code without tests? Gaggles of tests and not a comment in sight!
This is just trolling.
Regards,
Ross
Re:Gotta document that code... (Score:5, Insightful)
You could continue along these lines, and get to a point where it would be obvious what the code does. The comment in that snippet also addressed "why", in addition to "how". I would move the "why" explanation into a document that defines the protocol.
Good Code vs. Comments (Score:2, Insightful)
Comments are important. However there are different types of comments each with varying degrees of priority. Comments are primarily code documentation. Code generally starts with some sort of design and design documents are the first stage of code documentation.
Designs don't have to be monolithic war and peace style documents, rather very high level documents describing the purpose of the code. This generally gives future maintainers of developers an idea of the effect changing the code will have on an application.
Class Documentation / API Documentation / Java Docs / Perl Docs / .Net XML Docs are in my opinion are the most important forms of code documentation. I very much enjoy reading articles about programming concepts and designs. But when I am coding, it is the API documentation that I spend most of the time reading. My favorite languages are those which provide a large library of useful classes that I can reuse. perl, php and Java have large online communities that produce reusable library. This has two effects.
Writing such small reusable libraries generally the documentation will be very good. Each reusable library has documentation that allows other programmers to figure out how to use them. This means people writing these libraries are not only good at writing reusable code. They are also good at instructing others about how to use such code. Over time they become experts at documentation and serve as role models for others developer. .Net is an example of a large development group accepting these practices and now trying to embrace such strategies. But there is a much more interesting aspect to this.
Developers using these libraries become very good at using libraries. As programmers become more experienced, they progressively become more adept at finding reusable code and being able to make it part of a consistent unified solution. Developers who are practicing these techniques are becoming very good at designing and documenting reusable code. Having this community of code exposes developers to an enormous amount of high quality well documented code. This not only allows them to be more efficient developers, but teaches them to be very efficient designers. These are the people who become the respected technical leaders and in the optimistic case your boss or the senior programmers on the projects for your work. Perhaps you are one of those programmers and other a benefiting from your use of such tactics.
The least import type of code comments are the one or two lines before the while loop. These types of comments document the code at a micro level. At this level you rarely need a lot of comments. In most cases a competent developer requires the ability to decompose the code and this level without a lot of comments. This type of comment is never the less on the forefront of most discussion about code comments. Less experienced developers general can figure out the code is difficult to maintain but may not know exactly why. Not having the experience to point at exactly what makes the code difficult to maintain they assume it lacks sufficient documentation. This argument seems almost immediately logical. Unfortunately there is a flaw in this logic.
Just because code is difficult to maintain or enhance does not indicate poor documentation. I have maintained lots of well documented code that required hundreds of hours of modification to fix simple bugs or implement small changes. Several years ago I was asked by my company to help when a new application was released to our clients. This code met the acceptable requirements for code documentation. Each file had a header with modification history including date and developer information. Comments we also placed liberally throughout the code. This projected resulted in a single release and is currently being rewritten from the ground up. When I was asked to assist with the analysis the code documentation helped us quickly conclude the application would not be a viable replac
After coding for 22 years... (Score:3, Insightful)
Re:Top Ten Code Comment Do's List (Score:1, Insightful)
Re:Gotta document that code... (Score:4, Insightful)
Never tell me you are adding shifting the varaible by 4 bits, instead tell me, you are converting from bytes to 16 byte blocks due to a chunks size conversion because that's the size the output device expects blocks to be written in.
Don't tell me you are swapping variables, tell me why the values should be exchanged.
Don't tell me you searching for the max value, tell me what the max value is used for when you find it. That sort of concept.
One easy way to do that, is to look at code and the comments. If the code and the comments could get out of sync because you changed the implementation, the comment is wrong. You documented the how not the what.
There are cases where the how is important, especially when there are things where the "how" doesn't behave naturally. Oh, this sorts numbers, but it is intentionally sorting the ASCII values of the numbers when represented as a string. That'd be very useful to know. I'd expect a sort to work based on the binary values.
The other rule I remember from code complete, and from "Writting Solid Code", was the concept of laying out the pseudo code that explained what you wanted to do at a high level. Then filling in between the comments with the implementation. It was a very good way to end up with documented code.
Kirby
Re:The problem isn't lack of comments (Score:3, Insightful)
Choice of language has a lot to do with the readability and lack of, or need for heavy commenting.
Using java, PHP, Perl, etc, I find that I have a hard time writing methods that are much less than 25 lines long just due to the syntax required. PHP has the additional annoyance of not allowing method returns to be used in-line, requiring many temporary vars.
Something like the following in, say Java: Becomes, in PHP: Contrast both of these with an equivalent in Smalltalk: Granted, this is just a dumb example, but in practice I've found it vastly easier to write understandable, orthogonal methods in Smalltalk than in any other language I have tried. Combined with a good following of naming guidelines (that are followed pretty strictly in Smalltalk libraries) and its pretty easy to avoid spaghetti code.
Oh well. time for bed...
Purpose of comments (Score:5, Insightful)
I'd say you're right, comments are more important. Clearly-written code should make how it's doing things obvious, yes. Comments, though, should say what is being done and why it's being done the way it is.
Re:Gotta document that code... (Score:5, Insightful)
1) production code is not a tutorial of the C(++) language. It's okay to assume the reader knows their stuff. A bad example: 2) production code is not documentation on the APIs that it uses. APIs have their own documentation, the reader either is familiar with it, or can find documentation. A bad example: If the API is only used in one file, then you could point at the documentation right where the header is included. If it's used on a project level, then it should be pointed to at the project documentation.
3) comments are just as much about why you didn't do something a certain way as it is about why you did do something a certain way.
4) the obvious; name your variables correctly. Instead of: use 5) if you are implementing using a spec, somewhere in the top of the file describe the revision of the spec. Additional comments can describe the section of the spec that they relate to.
For example: 6) NEVER put actual values in comments. For example: The code already shows the actual value, and all too often the comment doesn't get updated.
Sometimes it's okay to list the possible values: but I only prefer that when this is the _only_ place where it is used. Otherwise you'd use enums and/or refer to the documentation section/page
7) write top level documentation to explain what the software is actually supposed to do. It's amazing how often this is missing. Write one bloody page that describes to a programmer that doesn't know ANYTHING about the software what the hell it's supposed to do, and how it's accomplishing this. It also helps tremendously if every file has a little description in the header. And I'm not talking about what license the code is distributed under.
Comment removed (Score:1, Insightful)
Re:After coding for 22 years... (Score:3, Insightful)
Re:Even more annoying... (Score:2, Insightful)
Re:The problem isn't lack of comments (Score:3, Insightful)
Re:Gotta document that code... (Score:1, Insightful)
If only all mistakes were that well commented
Re:Top Ten Code Comment Do's List (Score:2, Insightful)
Give proper name to function and parameters so that all this becomes evident. assert() paramter precodintions at begining so restrictions will be self documented. Make sure that function has simple semantics so return value is also evident, on rare cases when you cant do this add a comment.
2. Add comments to each file you modify so that over time, the file becomes better documented.Refactor each file when you modify and found them not obvious: to make them obvious. Commenting will not fix this, you are just introducing pieces of documnetations that can/will get ouit of sync.
4. Use dividing comments like a line of dashes to seperate blocks of codeSeparate them in different functions, that you can write tests agains individualy.
8. Tag your bug fixes, code enhancements with a comment followed by a dash, date, and your initials. This is essential for large projects or for anything you will be working on for more than 6 months.Use facilities provided by your source control management tool. cvs/svn/clearcase/(...) has annotate, blame, praise fuctions: use them instead and you will be able read them even after 6 years.
Format your comments so that multiple line comments line up on the left hand side (increases readability)Write them on top of commented item, this way they will not go off screen, you be able to print for them more without much fuss.
Don't count on java doc or equivalent as being good enough code documentation.Extend when you find the need for it.
Re:Even more annoying... (Score:3, Insightful)
Yes, it's worthless and childish. What would have been better? This:
numberOfApples=5;
numberOfOranges=2;
print(numberOfApples+numberOfOranges);
If code is well-written and uses good abstractions, good variable and function names, and short functions, it needs far fewer comments and is more understandable.
Re:Even more annoying... (Score:1, Insightful)
It is not the best way to validate user input, but it is better than no validation.
Re:Top Ten Code Comment Do's List (Score:5, Insightful)
I'm working with a 4GL, and the stupid comments are driving me more insane, especially the GPs no8 - tagging. I HATE tagging with a vengeance - that's what version control is for. Even worse is the unbelievably moronic practice of commenting out the old code and putting the changed line below it. We get one line of code replaced by 3 lines of comment and a liine of code - the comments are two lines of tags marking the start and end of the changed block and the old line of code - which is often only 1 character different from the new line. I WANT TO HIT THE WHOEVER STARTED THIS - REPEATEDLY.
For example I have been working on a 900 line program where 400 lines are 'comments' - sometimes you only see 1 line of code per page. Now imagine the effect upon search tools - you want to use find+grep to look for code to change, and 95% of the hits are 'comments'. It's got to the stage where I have written a program to strip all the comemnts for our code and save the result. Don't get me wrong I like real comments - ones that tell me something useful like why the code was written, or any gotchas - but when the signal to noise ratio is this low I won't even worry about losinginformation, the performance hit of all this garbage is too much.
Please, don't comment for the sake of it, comment only when you have something useful to tell the next coder to read the program - but do write these informative comments.
Re:Top Ten Code Comment Do's List (Score:2, Insightful)
assert() is only used during development. By the time it will be embedded in a released fly-by-wire system it was already tested extensively. If not than that is your real problem! Whole point of using asserts is to fail fast during development, so that errors become painfully visible, with a clear message: FIX ME NOW!
Re:Top Ten Code Comment Do's List (Score:4, Insightful)
Re:Top Ten Code Comment Do's List (Score:2, Insightful)
Moderate -1, WTF! There is no reason whatsoever to keep old code in comments; that's what source control is for.
My $0.02, and doing this has saved my butt numerous times when you're sitting at the implementation phase, ready to go-live, and something fails last-minute. (testing be damned!)
You know, that explains a lot. Never mind then...
Re:Top Ten Code Comment Do's List (Score:3, Insightful)
That way you can look at the "clean" code that the system is using and automaticly roll back all changes made to some or all files on a given date. You can even use diff to see what changed over longer periods of time in a given function. And it's automatic so you don't need to wonder if you realy rolled back the code to 12/15/04 you know it's what's in production.
And you get a simple place to comment the scope of what you where fixing / working on over several files. And can clearly see what files where changed for this fix.
I must respectfully disagree. (Score:4, Insightful)
1. Comment each function
- Function name
Why do you need to repeat the name of the function? It's right there in the code.
Yes, and in some contexts that is precisely the problem. Depending on the language and editor(s) you are using, embedding the function names in comments can be very useful.
For example, if I use an "FC" command in a Unisys 2200 mainframe editor (say ED or UEDIT) to show all lines starting with "C" (comment lines) in a Fortran program, the results will be confusing if the function names themselves are not specified in a comment line. All I will see is comments with no context.
By adding the subroutine or function names in the related comments themselves, that missing context is restored.
5. Put in a '?' comment for code that you do not understand (good for function headers)
Code with personal annotations should never be released.
While I agree with this part,
If you don't understand it, you shouldn't be working with it; go find someone who does understand it instead, or stop and work it out.
this part of your comment seems limited to "perfect world" scenarios only.
I've spent most of my career working on mainframe code that was either originally written by people at other organizations or companies, or that was written so long ago that the original designers and coders were either retired or deceased.
When making a first pass at understanding such code, I've found it to be quite useful to leave various comments in the code so I have a good idea about my level of understanding the next time I have to come into that area of code.
I've also found such comments useful when left in the code by others, since it reflects their level of understanding as well. Some of the stuff I'm looking at now was originally coded in the early 80's and rewritten by my predecessor, and the comments he's placed in the code have proven to be invaluable to me, even though some of them were speculative in nature. Something like "What does this code do?" in his comments often alerts me to a tricky part in the logic that I'll want to pay special attention to.
FWIW, question marks and other comments/speculations are commonly used when working on someone else's previously-written code, at least in my experience, especially when that code is only intended for use in-house (the source is not released to customers).
8. Tag your bug fixes, code enhancements with a comment followed by a dash, date, and your initials. This is essential for large projects or for anything you will be working on for more than 6 months.
Once again, nothing with personal annotations should ever be released into source control. Not only should I not need to know who wrote or changed a particular snippet of code to fix a bug, I shouldn't even be able to tell by looking at the code.
When working on code that was written in-house, and which is intended to stay in-house, I *want* to know who made a certain change and why it was done. That type of notation can save me (or another support programmer) a lot of time.
While those types of details might be handled by the source control system(s) that you work with, keep in mind that some of us work on platforms where analogs to the UNIX-like source control systems many people are used to simply do not exist (and often such a thing isn't really needed).
When I did Unisys A-series mainframe contract work at a small company in southern Minnesota, they used the unparsed end of each COBOL line as a comment area, and one always placed their initials and a date there so people knew who did which changes and when those changes were created. The editor they used (CANDE) even had a special setting to automagically place a change mark on the end of each line that was modified.
A si
Re:Top Ten Code Comment Do's List (Score:3, Insightful)
Uncommented potion code (Score:2, Insightful)
Most of your code would look like this then:
PotionCombo potionCombos[] = {
{ WATER, SOIL, MUD }
{ WATER, BEER, CHEAP_BEER }
};
A comparatively small loop function can check the list:
/* checkPotionCombo
Check a given combination of potions,
returning the potion that results.
Returns: the combined potion, or an empty
flask if the mixture is invalid.
*/
function checkPotionCombo(Potion a, Potion b) {
REQUIRE(isValidPotion(a));
REQUIRE(isValidPotion(b));
Potion result = EMPTY_FLASK;
of our combination lists (lower potion
number first) */
a = min(a,b);
b = max(a,b);
for (i=0; i<NUM_POTION_COMBOS; ++i) {
properly */
assert(isValidPotion(potionCombos[i].a));
assert(isValidPotion(potionCombos[i].b));
assert(isValidPotion(potionCombos[i].result));
arguments
*/
if ((potionCombos[i].a == a)
&& (potionCombos[i].b == b)) {
result, and stop searching */
result = potionCombos[i].result;
break;
}
}
ENSURE(isValidPotion(result));
return result;
}