Comments are More Important than Code
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?"
I used to grade student's code as a TA at my university, and I'll tell you what is more annoying than NO comments, this:
/* print "Encrypt message..." to the console */
printf("Encrypt message...");
and then followed by about 150 lines of uncommented spaghetti code
____
~ |rip/\/\aster /\/\onkey
Just go ahead and use the long names, that alone will reduce documentation/commenting
--Joey
Has he read the ones here?
Before any liberals are tempted to mod up one of my comments, a word of warning: I'm actually making fun of you.
...where comments are more important than articles.
Take off every sig. For great justice.
How about Perl's POD Documentation? I do a lot of hacking of Matt Simerson's Mail::Toaster and Nictool projects, and I find that the Perl POD Documentation system, combined with well-named variables is easy on the eyes, and leads to it being well interpreted by an outsider.
May this post be indexed by spiders, and archived for all to see as my Internet epitaph.
Comments can be misleading, misinterpreted, out of date, or just plain awful.
Code is self-documenting.
I spent a minute looking at my own code by accident.
I was thinking "What the hell is this guy doing?"
with thanks to bash
Always comment. Always. I'm not a career coder, but I've done enough to know that if it's a project of any noticeable size at all, and you intend to read the code later, take the extra few seconds and COMMENT THE STUPID THING. It makes life a lot easier. The only thing that probably doesn't need commenting is a simple BAT file or a shell script. Comment!
I think having comments in your code is a matter of preference. I find it nice to have as few comments as possible so i can read the code better.
Obviously thats my preference, but i feel comments are optional (unless dealing with really complicated code)
cha-ching. money baby... money
Use Visual Basic! More Comments and zero code.
Science without religion is lame.
A good development process with commented function names and function purpose as the framework for the project will assist in the coding as well as provide more than adequate commenting on a project (shouldnt code the how, only the purpose). Its workes for me in college (sr. UIUC), lets hope it continues in the business world...
"this is the gloaming"
radiohead
I work with java, with javadocs. There is nothing more frustrating than reading a 500 line program and having the actual represent 20 lines with 480 of the lines filled up with comments. Just don't over do it. Another thing, in school they teach you, "You should comment every line". That is silly, not every line needs comments. I believe in a black box approach to your programs, if you can comment outside of the function and describe what is going on inside of the different blocks. I can't easily reuse that function if it is properly commented. I don't want to know what is going on, but if I know the arguments, the return-type, I am ok.
---- Berlin Brown http://www.newspiritcompany.
When you write bad code, good comments won't save you. The other way can sometimes work. Spending all your time on comments seems like only talking about solving an engineering problem, not actually doing it.
What keeps me going is my inertia.
And this, my friends, is one of the reasons why offshore outsourcing is doomed. You understand comments are important. For people in India schedule is far more important than comments. So they'll cut&paste shit all over the place and leave it uncommented. If you happen to have to work with it, your hair will turn gray pretty quickly.
This works for code I write that nobody else will ever maintain. Even then I can get tripped up, I'll have to lean back in my chair and try to remember what I was thinking when I wrote the code.
But if you write code you're getting paid for, or code for an organization, anything but personal stuff, write good comments. Variable names might give a good idea about what data the variable holds, but it does not tell us much about how it is used.
When I took my first programming class, the most frustrating part was the documentation. I thought it was retarded and stupid and a waste of time. But now I realize it is very important once you write something more significant than "Hello World".
Rosco: "If brains were gunpowder, Enos couldn't blow his nose."
Good organization and descriptive variable names are no substitute to actually noting what the heck you're looking for or trying to accomplish. Checking a bit flag with a nice name (such as "input_recvd") is not nearly as useful to the maintenance programmer as a comment which says "test bit flag set by keyboard input routine - "1" value indicates input complete"
> 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.
Yeah, it should be enough, so long as you're writing a very well known algorithm. Like, say, heapsort. Small functions with no side effects, good variable names and scopes as limited as is reasonable for each variable. I mean, technically, the code tells you exactly what the code does.
Sheesh. Comments important. How important they are varies with the algorithms you're implementing. But they're important. Clear code with less commenting may be more valuable than complex code with more commenting. That's hard to call. But in the end, you have to know what code says. And if it's clear enough from the code, fine, then the code IS your comment. But that's not a safe habit to fall into, because then you have the mentality that code is always enough for a comment. This gets you into trouble. (Big trouble.) See any piece of complex C code. =)
In my opinion, comments are useful -- but literate programming is where it's at if you're looking for the best way to document your code.
Knuth did a lot of work in the area -- if I remember correctly, all of the sources to TeX are written in a style understood by the "web" literate programming tool.
There was also a good article by one of the Perl folks (Nathan Torkington? M.J. Dominus? Chromatic? I can't remember.) on POD, and how although POD wasn't literate programming, it was still useful. That article was great in that it showed a middle ground that may be more palatable to your non-LP-fanatic programmer.
That being said, I prefer full-on LP for large projects.
unixkb.com -- articles on practical Unix issues.
i do a lot of code reviews at work and nothing makes me happier than good comments.
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.
My opinions are my own, and do not necessarily represent those of my employer.
The last word in documenting your code is doxygen. Especially the @author tag so you know who to yell at. I find that keeping individual functions short and then documenting what each one is supposed to do / take as parameters / return is better than comments within large blocks of code. What I hate though are large blocks of commented code. I guess sometimes the developers is too timid to remove old code, but seeing them always makes me wonder if the new code really works, and if so why is the old code still there.
Philosophy.
Maybe in 1970, but nowadays commenting is so ingrained in the coding process that code review and similar activites don't even start unless the code has sufficient commenting. This article is really only relevent now for start-ups were coders are not necessarily answering to any company guidelines, but any decent start-up knows they need a decently commented code-base (look at any of the successful open source projects out there).
But impossible to follow, is this:
Only comment the things that are hard to understand. The problem here is that you probably understand everything you're writing.
One way out might be to have a less-talented programmer give it the once over, and point out anything s/he didn't understand, for you to comment upon.
That, and as Dr. Stroustrup (Bjarne) said in class today, your code constructs should be directly analogous to what they are trying to describe in real life... But I guess this goes down to self-documentation.
I would say that reasonably well written and organized code does not need extensive documentation for you to come back to it later and maintain / extend it.
I would also say that such code by its self is totally inadequate if someone other then your self needs to come along and maintain / extend that code.
The real problem is not code in general, but code written under an immediately approaching deadline. I am in the ass end of a crunch that has gone on a bit longer then anyone would have liked it to. Code written this time last year is still pretty good. But code written in the last few months is pretty rough from a long term maintainability standpoint.
Therefore, I suggest this:
When writing new code, make it self documenting, and comment at your discretion.
When fixing bugs frantically in the ass end of the project, Comment extensively.
END COMMUNICATION
people don't comment code for two reasons:
1. they're in a rush
2. they're lazy
if you're being lazy then stop. add some basic comments which will help someone else, or even yourself when you come back to the code in the future. long names help but they aren't enough.
if you're in a rush then you probably should have started sooner. try to get more time if you can. if you rush thru the code now you're going to be in even more of a rush later with all the time you waste when you come back to your old code and have to painstakingly work your way it.
-mr silver
if you're doing projects for work you'll tend to come under fire for taking too long and not meeting deadlines on time because you're taking all the necessary time to spend commenting, but then later on when you have to review your project to make additions or have someone else do the work you come under fire for not having spent enough time commenting
it's a real catch22 situation. plus since it's for work, having it commented or not really doesn't make much difference... at least to me.
There is a reason for COBOL.
There is a reason for C.
There is a reason for ASM.
Why cross the bound and use the worng one for wrong reason?
Comments ARE NEEDED to help understand "paragraphs" of code. Like the use of a subroutine or why the program got this point in processing.
Using variables like comments does not make the code easier to understand unless you are using COBOL.
Writing code like a(i++) =+ b(--j); does not make understanding easier. Nor always makes code run faster.
Writing comments like MOV AX,BX ; move AX to BX
makes the program more self documenting.
So in the end. You are mostly right. Adding comments where they are needed and ARE MEANINGFUL make future maintenance easier.
Now if only the next guy that fixes the code will actually REMOVE unneeded code and COMMENTS and place new correct ones in thier place.
Variable names should be proportional to the size of their scope within the code.
How about, comments for some, no comments for others!
But seriously, only comment what's complicated... anything easy (to other programmers, not just you) doesn't need to be.
I knew a guy who did pre-comments, where he would write out the steps for the loops, showing nesting and such before actually writing the code. It worked pretty good because you had an overall idea before you started digging through code.
"There's a subtle reason that programmers always want to throw away the code and start over. The reason is that they think the old code is a mess. And here is the interesting observation: they are probably wrong. The reason that they think the old code is a mess is because of a cardinal, fundamental law of programming:
0 69.html
It's harder to read code than to write it."
From Joel on Software
http://www.joelonsoftware.com/articles/fog0000000
Always comment.
I hope that after I die the one word people use to describe me is "resurrected."
Why on earth do we even have commenting? I mean, we went through the whole programming language concept precisely to make instructions to computers human-readable. Ideally, commenting should be obsolete - the language and its syntax should make it obvious what needs to be done.
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?
As one of many, many people coding a very large software project, I have come to realize just how important comments are. My job is to test various pieces of code. Often the code is very poorly documented and I may end up spending days just trying to figure out how the code works. Even longer tracking down the bug(s) in it. If the person who wrote the code in the first place had bothered to comment it, I would spend A LOT less time (maybe no time) trying to figure out how the code works. But, since they skimped on comments (saving them a few hours), I'm left spending days working on the code, which costs the company a lot more in the end.
.. but then I'm the only person that does anything with it really. But, I think these guys have the solution if you have a boss wanting the comments for true.c :
http://www.cenqua.com/commentator/
Don't blame me, I voted for Kodos
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.
Simple Machines in Higher Dimensions
The amount of commenting necessary depends on the level of experience of those who will be modifying the code later. Experienced programmers will be able to figure most of the flow of the program (and therefore the pieces) fairly quickly, whereas junior programmers will require explaination.
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
is a reasonable choice of name for an integer variable denoting a year, but the year of what???
When code is first being written, the context is in the coder's head and everything is crystal clear and obvious. However, remove that immediate knowledge of the code, and the name intYear becomes far less descriptive.
Short of using 80 character variable names and destroying readability, you need comments to provide context so that the meaning of the value stored in the variable requires no interpretation. The same applies to methods, objects, etc.
Just write your whole program in comments.
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?
Rosco: "If brains were gunpowder, Enos couldn't blow his nose."
UsngShrtCmtsIsOftNotEnghAsOneMyNdToReWrtShtInTheFt r.
The problem is usually functions that are too long and are not orthogonal. Write short, orthogonal functions and you'll see your need for heavy commenting go away along with the need for long variable names.
A story I heard from a coworker; some years back he worked as a coder for a school district in the state of New York.
He had a cow-orker who despite not knowing dittly squat about coding managed to got himself hired as a coder.
Knowing the said cow-orker is incapable of writing a single line of code, he and his OTHER coworkers had this git write the comments for their code instead.
Some time later the cow-orker left on his own accord and his replacement arrived. Their advice to this newbie was "Don't worry about the comments, they're all wrong."
Moral of the story, the comment is only as useful as the person that wrote it.
If it was hard to write, it should be hard to understand!
One way I've found to write well documented code, is to first write very general pseudo code, then for each block of pseudo code write really code (or a function).
//initialize the variables //Execute the operation 1000 times //generate output //clean up //return
So my code starts like:
And each of those lines can either become a function, with more documentation within, or a small block of code.
This not only helps to force me to document (which I hate to do) but it allows me time to think of the algorithm that I wish to use, instead of the nitty gritty code.
Also, don't forget to liberally use whitespace. Separating blocks of code with newlines is an easy way to help people read your code.
Now if only the next guy that fixes the code will actually REMOVE unneeded code and COMMENTS and place new correct ones in thier place.
I've found old comments in my PHP codebase before and sometimes they throw me off. To make a habit of deleting them when you're deleting old code can be tough. There is no way to distinguigh between old comments and new ones either... because all comments look the same.
Maybe it's time for XML to save us all?
The dangers of knowledge trigger emotional distress in human beings.
Short, descriptive variable names Vs well commented code are good to keep your employer dependent on your services since someone else that is forced to work on it will probably just wind up re-writing your code in the end to save time.
Is that they often end up not matching the code.
I admit that I'm lazy and that's probably the biggest driving force behind not doing a lot of comments.
But, I find that fellow developers who do comment heavily end up doing this: they write some great code along with some great comments. Then the code is refactored about 20 times, and the comments end up completely out of sync.
And I find this code far more frustrating than uncommented code with meaningful variable names and small functions with meaningful names.
I agree. Thefor documentation.
JEF RASKIN, professor of computer science at the University of Chicago, is best known for his book, The Humane Interface (Addison-Wesley, 2000), and for having created the Macintosh project at Apple. He holds many interface patents, consults for companies around the world, and is often called upon as a speaker at conferences, seminars, and universities. His current project, The Humane Environment (http://humane.sourceforge.net/home/index.html), is attracting interest in both the computer science and business worlds.
For those who don't know (which apparently includes whoever is in charge of the linked article), Jef Raskin passed away this february. You can view the official press release, or read more about his contributions to computer science. I don't know when the article was written, but it seems it should mention that Raskin has passed away. In any case, his advice about commenting is good, just as his advice on user-interface design has always been lucid and helpful.
Somtimes its just plain old fun to read what people wrote in comments because you actually can get some insight into what was going on... its less formal than output.
seeing other's code-in-progress is always reassuring when there are things like:
/*good lord do i hate this effing function!
please god just make it wooooooork!*/
makes me feel not so alone.
as for variable names, when I was in my first comp sci class, I used to name variables obscene things (I was in highschool), which I thought was dandy until I realised that I'd have to go back and change everything so I could submit it to the instructor.
sigh..
System.out.println(syynnapse.getSig());
"comment should be the default, with a way to signal the occasional lines of code."
Where do you work?
A swan song by one of the designers of the original macintosh, sadly deceased.
RIP
grammar-lesson free since 1999. (rescinded - 2005)
Imagine my relief when I came upon a helpful comment:
All it took was one comment to put my mind to rest: no, it's not just me being stupid in the present. This code seemed this terrible back then, too.
Comments save the day once again.
If you need comments to understand your own code, then your code is sloppy and you should fix that problem first. Writting sloppy code is like having bad handwritting. Fix your handwritting. Comments get out of date and are a topic all their own. Someone who writes sloppy code will probably write sloppy worthless comments as well.
You should also code first because you know what a function is supposed to do. When it does exactly what it's supposed to do then comment it. Otherwise your comments will be more along the lines of wishful thinking and lead to more confusion.
You should understand the language well enough that you can keep in your head everything the code is doing and if not, understand the language well enough to be able to read the code to see what it's doing. Comments are not going to help you debug a function. You need to be able to read the code itself to be an effective debugger. Only once it is debugged can you confidently place in comments that say what the function does. Otherwise, it's just wishful thinking.
The most commenting I do before writing a function is a rough outline of the steps the function needs to go through. Only after the function is done and does exactly what it's supposed to do, do I comment it.
I've gone back to code (thousands of lines) I wrote in BASIC 10 years ago and can understand exactly what's going on despite there being no comments. Same with stuff I've written in C/C++. Comments are not essentional if you can read code like a book. Which, a professional programmer should be able to do.
www.wolf5k.com has an obfuscated version of Wolf3D written in Javascript. I went through and deobfuscated the code, figured out exactly what it does and then commented it. I then took the deobfuscated version and translated it to C++. I did the same with the Gavare ioccc ray tracer although the results havn't been posted on-line yet.
Deobfuscated Wolf5K
If you want practice reading "bad" code, deobfuscating programs is great practice.
Ben
Work Safe Porn
Tell that to the boss when the code is due. You will soon learn what is REALLY important in the real world.
Without working code, there is no product. Without product, there is no money. Without money, hello unemployment line.
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?
This is not algebra in high school where you lose points for not showing your work. This is the real world where an application might have 100's of lines of codes, maybe 1000's. It might be a bunch of classes in java working together. And then there is the logic, the work flow.
Plus, many companies use peer review for raises and advancement. If your peers have a hard time understanding your code, it will hurt you later.
Most people today don't work 30 years for one company. That means someone else will get stuck with your code.
Now either you will give that person months to go through all the code, to try and figure out how it works, or you will have code with comments that will help him hit the ground running.
Rosco: "If brains were gunpowder, Enos couldn't blow his nose."
At least that's what someone who comments told me. :)
Agreed. I am currently (this very night) going through an assortment (few hundred) of php documents that run a friend's business website.
He had it done by a company that eventually outsourced it to.. guess.. India.
Within an hour I've found 3 non-working subroutines in the administrator login menu, 4 unprotected directories on the webserver containing files which hold among other things the SQL database login/password and not ONE stinking bit of the code is commented. There's cut/paste jobs abound, even containing referances to free php-script type sites.
It's an absolutely horrible job. Although the site graphics/layout is quite excellent. =)
I have a feeling the company hired produced the color scheme and layout then outsourced the backend.
using short, descriptive variable names 'should' be enough
Aren't they on the opposite ends? I find it much easier to have descriptive variable names which are relatively long (~25 chars in C++). Not all variable names need to be that long (most local variables don't), but I often find that using long descriptive variable names makes comments unnecessary.
Also, I don't think there is some magic ratio of comments to source code line (like 1.5 comment lines per 1 line of code). If someone tries to stick to such ratio, it would be a waste of time in some cases and insufficient in the others. The bottom line is that if code is trying to do something "clever" (tricky algortihm or complex logic flow) then be generous with your comments. Otherwise, you can get away with just a few comments and save yourself some time. If you are just starting to program, you won't go wrong putting more comments in. Otherwise, let your intuition and experience be your guide.
One final observation is that I find comments at the beginning of source file most helpful. A paragraph or two describing what a heck is going on can go a long way to helping me understand some key ideas without having to skim through the entire file.
"You mortals are so obtuse." -Q
Software is the only designed/engineered product that doesn't have accompanying documentation such as a schematic, blueprints, etc.
Comments would be suruflous if there were a design document that accompanied the final product. By looking at the code one would be able to determine where they are, similar to standing in a house and knowing where in the blueprint you are based on your surroundings. Comments are not sufficient because they can't communicate the context of your position within the code; rather, you must read the comments to see what the code is doing, but you must examine the entire routine(s) to determine the methodology used to solve the particular problem(s). Until software has a blueprint-like document that goes with the code and the delivered binary/executable, comments will be necessary but woefully inadequate.
An interesting article on ZDNet on Documentation is good, but source code is better
Good documentation practice from Linux.com.
the total lack of formal methods in the software we develop today means we have to use comments to document our intentions and design decisions. This is obvious to anyone who has some experience in the industry. If we had formal specifications a large number of comments would be pushed up from the code into the specification.. but seeing as we're currently incapable of working with more than 2 files at the same time (many people have trouble keeping their header files in sync with their source files unless the compiler complains about something) that's not going to happen any time soon.
How we know is more important than what we know.
If your code is clever, then you must document it.
IMHO, writing clever code is a bad design principle.
From that perspective, good design reduces the amount of comments required. You are correct, but perhaps your coworkers are more so.
Indian engineers are probably fairly well paid, considering their cost of living,
If the US doesn't help Mexico achieve a reasonable standard of living (no matter who is at fault for the lack of it), then Mexico will come to the US. Those people have a legitimate reason, you can't stop them.
What keeps me going is my inertia.
That's an extremely contrived example, but I *have* seen code where *every* step was commented just like that. That woud be great if it were an explaination of the reasons behind some complex algorithm, but more often it's just a rehash of what's obvious from the statment itself.
"Times have not become more violent. They have just become more televised."
-Marilyn Manson
Seriously, shouldn't it be a balance between good documentation and good self-documenting code?
The above would be far more useful like this:Now the intent of the method is clear, and anyone coming along who wonders why it's hard coded will know under what circumstances they should change it to a formula (namely, if MyClass becomes capable of meeting the Magilla criteria).
Comments can be good, but they should always be a guidepost to the intent of a block of code, and not attempt to explain how the code achieves that goal.
Stop-Prism.org: Opt Out of Surveillance
Too often you know what you are trying to do but make a mistake. Self documenting code is only useful if the code is free of mistakes. IMHO it is better to comment what the code is supposed to do.
If the intention is clear then it is easier for others to determine if the implementation is correct.
Intentions also better describe why particular design decisions were made.
-- Rich
Comments are very important, however you need to figure out the right level of detail that provides as much documentation as possible, without taking too much time away from coding (because then you'll be likely to leave the comments out).
Incorrect comments are worse than no comments at all. In an ideal world, you'd figure out what you want to do, write the documentation for the function, then implement it, documenting any lines that aren't obvious. However, life is never like that. Sometimes you need to modify a function to make it do something else. If your comments are too long and verbose, you'll be tempted to not change them, which is worse than not having them there at all!
Therefore, you should keep your comments concise. Don't waste your time writing detailed comments for a simple function, or one that is likely to change tomorrow. But when you finish a complicated function and get it to work, definitely make sure it's well-commented, so you don't have to worry about it again.
Well structured and well written code is obviously more important than having comments. Allow me to give an example. I once ran across a single method that was 10 pages long! The variable names were all completely unhelpful, and the code itself barely worked. It was clearly written by someone that didn't know how to program. It had some comments, but I still couldn't understand what was going on. No amount of commenting would be able to help something so awful.
Contrast that with well structured code, wherein the methods are relatively small, the methods and variables are well named, and you can have a usable, maintainable program with no comments at all. Comments are nice for the sections where what's happening isn't obvious, but if you need to sit down and comment every line of code you write in order for someone else to understand it, you're writing some very bad code.
Will MDA help solve this? The on-site developers create the various models, which serve as high-level documentation, and whatever can't be automatically generated is off-shored. There would still be a lot of code to write, but it would be easier to understand with the PIM/PSM available.
That probably will only help in large developments off-shored, and likely more of a dream than a reality.
If you're doing OO, invest some time in a good unit testing framework, like xUnit. I'm inclined toward the agile method of test-driven development (flame away), so I would prefer that any code I have to maintain was written *after* the tests were constructed; however, I've seen valuable unit tests which were clearly either automatically generated or manually written after the code under test was completed.
As long as you commit to maintaining your tests, refactor all you want and rest assured that as long as your tests pass you're in good shape.
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.
..then you or your employer is an idiot, plain and simple.
First, I just have to get this off my chest: I think this is pure B.S. Coding styles vary so much, that if you can't recognize your own code, then programming is something you barely have a hold on.
Now, as to answer: code should be readable, especially using mixed type names, a consistent naming style and comments for non-intuitive constructs. But -- and this is a big but:
If your code is meant to be shared with other programmers and you don't have a design document...
If you have a project that needs support from more than one programmer (i.e. any commercial enterprise save DIY shops), then blaming "lack of comments" is just displacement. Blame the project manager instead.
Of course, there are always exceptions. When I was writing low-level code that manipulated hardware registers, I wrote a multi-line comment before each line of bit-fiddling code, complete with what the code did and a cross-reference into the hardware manual. Something like:
What a fool believes, he sees, no wise man has the power to reason away.
Way to generalize an entire country over something you clearly know nothing about.
I feel like properly commenting interface functions is a good way to go.
If people can't understand the code after that, then maybe the interface needs to be fleshed out more.
But I think this stuff is really language specific. Different languages need varying levels of comment-documentation to be understandable.
I heard that there was a language in the '70's where the specification document was the program.
The compiler would actually compile the spec!
I am not a programmer. There was a time in my life when I thought I might become one but that folly has passed. When I was trying to learn to program I remember reading a comment by a veteran programmer: "There is a special hell reserved fro programmers that don't comment enough." From the little I know it would probably be helpful to someone trying to service something down the road to at least label routines by their intended function. Commenting every line is most likely not necessary. kk
When getting directions, do you need to have a tree or a traffic light explained to you or do you just need to know what to do at that tree or traffic light?
The greatest use for comments is mapping out the over all logic of the program. How does one method/function relate to the overall functionality/goal of the application, in what context will it be called, what other methods rely on this function etc.
Naming your variables is great, but if all it does is identify what that variable represents solely within the local scope of the method or function it's fairly useless when doing a code review a couple years down the road.
Well written methods with descriptive names are a good idea as well, and do lead to the 'self-commenting' coding type of approach, but speaking from my experience, comments are still the best way to clarify things.
The problem arises when I have to modify a portion of our business application (about 500 classes or so). On any given screen, we might have fifteen objects working with each other, and so the key to this isn't figuring out what the method and variable stuff does, but what the actual OOP design was. The code itself is usually very readable, but there is a lot of skipping around through various interfaces and helper objects.
This is why you can't count merely on self-documenting code, especially when you're working with polymorphism and OOP. Document at a design level!
Surely commenting comes as a result of a good design practice.
You start with a functional spec, from which a design spec is derived.
The design spec is then broken into functional units, which are each divided further and further until the code itself seems obvious.
The final design is given a walk-through to verify with peers.
This design could pretty much be converted into a set of comments, each of which describes how the code should function.
The problem comes when coders just give it a go, write stuff on the fly and don't bother with design. It could be brilliant code, but most often it's just plugging local holes without reference to the overall design.
Comments are generally a good coding practice, and should fall naturally out of a good design phase.
So your theises is that indian programmers can learn enligh and PHP but not how to comment?
I have know lots of americain programmers say the code documents itself. Many bad programmers think comments are not needed and it has nothing to do with where they are from but how they are taught.
Outsourcing may or may not be a serious issue, outsourcing may or may not be a danger to americain programmers but commented code, or lack of, isn't going to play a very large part in the outcome.
I mod everyone down who says "I'll get modded down for this." I hate to disappoint.
Comments are great if the programmer takes the time to update them when they update the code.Many times a chunk of code is doing one thing but the comments say another.
NOTE: I say "code" referring to function bodies. I strongly believe that every function should be clearly labeled and its behavior clearly defined. Javadocs, doxygen, C#'s XML comments, etc are EXTREMELY VALUABLE, no matter how obvious some descriptions may be sometimes.
// Outputs x to the console
Self-documenting code is THE BEST WAY TO GO, but far harder than commenting.
If the code is written properly, anyone should be able to glance at it and read it. Not a single comment should be needed at all, but unfortunately that's idealistic and unrealistic.
Comments exist for clarifying code that is inherently not self documenting. I believe comments should be the minority. If there is a comment, that means the code is confusing and requires clarification. Sometimes confusing code is a must for performance, to completing an implementation on time, or just because it wouldn't work any other way, but it should be avoided as much as possible.
You should try to build your code in such a way that you can't possibly think of what to write in an inline comment. This means lots of modularity: well documented functions even when they are only ever going to be called from one place.
You should look at your code and every line should read to you:
coutxendl;
http://brandonbloom.name
I think you can encapsulate comments directly into your code via interface/variable/method naming.
I find that for simple code that requires little thought, little in the way of comments is required. Sometimes comments just get in the way as the code progresses over time, and the comments don't. It's better to code with long descriptive variable names, and structures then depend on comments.
//Customer ID structure // ID number for the customer // Agent Name // Customer Name
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
Why do you think they call it 'code'?
-Eric Smith
And this, my friends, is one of the reasons why offshore outsourcing is doomed. You understand comments are important. For people in India schedule is far more important than comments. So they'll cut&paste shit all over the place and leave it uncommented. If you happen to have to work with it, your hair will turn gray pretty quickly.
no danger of that happening.
I don't see how taxing the wealthiest and giving the money to the poor has any connection whatsoever with offshore outsourcing. All taxing the wealthy does is drive economic activity out of the US.
Offshore outsourcing is about the greatest good for the greatest number. If you have to pay a programmer $60k in the SF Bay Area for him to survive in a more or less bare sustenance lifestyle, and you could pay a programmer $10k in India and let him live like a pasha, which would you rather do?
The projects I've been involved with have been ones where I can work as a single developer and do everything. In that case, it's most cost-effective to hire an American (namely me) because the overhead of hiring people in India only becomes viable when you need whole teams of people.
With people avoiding the CS major and computing careers in droves, because of its perceived dead end nature, there is likely to be a shortage of programmers over the next few years. Strange but true.
But that's then and this is now. In the mean time, I've shifted my career from programming and software design to multimedia development and entrepreneurial ventures. These are areas where it still makes sense to be here in the US.
I'm pessimistic about US jobs because I know the people in India are good people who need the jobs as much as we do. Slamming the door on them doesn't strike me as the answer. If there is a single answer from the American point of view, I think it's for each of us to become more competitive by working closer to end users and/or changing our careers entirely.
D
1. Self-documenting code is a myth. Often spoken of, never clearly defined. In effect, nobody knows what it is although it makes for a nice buzzword.
2. Name one programmer in the history of mankind who was rewarded for comments. What's that? You can't? Well, now you understand the problem a bit more.
>> For people in India schedule is far more important than comments. So they'll cut&paste shit all over the place and leave it uncommented.
You don't need to go to India for code like that... The West has its' share of bad coders. and even its' share of skilled coders who just skip the documentation.
http://request-header.info
So the importance of comments comes down to the issue of maintainability. Under the pressure to issue v1.0, comments (and even coding style & practices) often get short shrift. Other things are more important at that time, but it becomes "pay me now, or pay me later".
Personally, I believe in modular coding. Any module that cannot be easily and quickly re-written is too big. Then documentation can be reduced to interfaces -- required inputs, and produced outputs. But nooo ... everybody wants to cram more functionality into the calls.
is not comments in code. Having spent more than a few years as a maintainer of crap, I have to say that I have gotten to point of not putting a lot of faith in comments.
Comments come in a few forms.
1. Correct and useful.
2. Incorrect and seemingly useful.
3. Correct and useless.
4. Incorrect and useless.
and may favorite
5. Comments concerning the code that no longer exists.
Correct and useful comments are in the minority, a very, very small minority.
Over the course of a project various people will maintain the code, very few seem to maintain the comments.
Nothing is ever going to be perfect, but through my experience I can say there is one thing that holds true.
"The simplest way to solve a problem is always the most maintainable."
... speaking of bit masks, anyone seen the source for rpm? The way it handles command line arguments seems a bit silly really.
XML is like violence. If it doesn't solve the problem, use more.
In relational databasee, you don't want the same piece of information in two different place. One will usually be wrong. Let's get better programming languages that are inherently more readable. It's the wild west out there.
At work a couple of years ago I was assigned to update an MS Access/VBA (ugh) application that had been written by a different programmer a few years previous. Upon delving into the code I discovered two things:
1) There were no comments.
2) The mostly descriptively-named variables were all spelled wrong. I found out later that the programmer didn't speak much English.
It took me forever to figure out what the code was supposed to do, and I ended up just rewriting the application from scratch because it was so bad.
Good programmers never comment their code; it was hard to write, it should be hard to understand :)
As someone who is currently debugging code written for a homegrown database application (no comments, and several languages literally blended together). I vote for lengthy, descriptive, and functional comments.
Even further the programmer/administrator should not assume the next maintainer is of equal or greater intelligence. KISS the code, KISS the comments.
I'm just not that quick witted. I'm actually quite lethargic. Example: Sloth;-)
This is an old debate. And in my search for truth I've learned this: //Pre: //Post: Returns a copy of internal data.
1.) Comments can't help badly organized systems. No matter how elegant your code/comments in a bad system you will spend years extending it.
2.) Organized systems are comments unto themselves. When you have a system, that's blatantly obvious how it works via function conditions and data types, comments are superfluous.
3.) Wrong old documentation is the devils ugliest mistress. Something like this:
char *text_for_something(void);
It ends up implemented like this:
{ return internal_data; }
4.) Too much commenting makes code unreadable. If you have so many comments that you can see as much comments and code on the screen, it's probably too much. If you can page through and never see a comment, it's possibly too little.
5.) Write it, sorta forget it; go back and comment. Seriously, 2 days is long enough to make it vague and short enough to make it rememberable. So you can make it make sense for your 2 day seperated self. Maybe your 2 year seperated self will see it too.
6.) Guides are good. Filenames aren't very descriptive, maybe describe them somewhere so people can find their way around.
7.) I don't know what I'm talking about.
I'm going to weigh in against the long-term viability of the outsourcing scene. I have some hunches that I've yet to see tested, but there are also some that have been proven correct. As a result of my experiences, I believe that outsourcing through the language barrier will in time be proven to have been a fad. The whole thing is a false economy. Certainly, there will always be markets where you can find someone willing to provide a service for less than a local supplier. When the service doesn't seem to be tied to any geographical location in the way that software is practically universal (like english!), there will always be the temptation to chase estimated or hourly savings. The cost of interfacing between languages and remote supervision must be taken into account. Also consider the efficiency and accuracy that you can communicate with in your native language. Just for fun, grab a french-english dictionary and try to comment that code that you wrote this afternoon...but in french. Come back to it in a couple of days and see how well you can understand it. Consider also that currently, a lot of work is being sent to India. There's a reason that workers are willing to accept lower wages. The cost of living is lower. But what will happen if so much work continues to stream into India and it continues to carry with it foreign cash. As some workers increase their assets and income, others around them will demand more as well. So the savings found in India decreases and less work flows there. Bottom line: vigorous outsoucing cannot continue forever because all of the money flowing out of our country shrinks the deltas between world economies. And that will erase the conditions that made outsourcing attractive in the first place. Of course, that's just my opinion. I could be wrong.
What, Indians can't learn to comment their code? And for cheaper than Americans?
// This is not a sig.
What do you mean "some of them already know english"??
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..
There are three things the poor maintainance programmer who has to maintain your code needs to know: The What, the Why, and the How.
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.
www.eFax.com are spammers
I write PHP modules for various thing, usually following some API or other.
ExtractLatestSongFromRSS($rss)
I always use very precise terminology for what I write.
For instance, if I'm writing a script to parse music information from an RDF file, I'd call my functions something like
XMLFetchRssFeed($URL)
ParseRssIntoArray($rss)
that sort of thing.
XMLHttpRequest style function and variable naming.
For code only I will ever view, it's descriptive enough.
I've been the CTO and system architect for two software companies and have built some big software systems still in use today, after more than a decade of use and development across multiple, large teams.
I personally hate comments for all but the most complex blocks of logic. Why? Because no one ever updates the comments, and pretty soon you have code that doesn't match the comments, and you end up wondering what's really supposed to happen. Comments end up as little fossilized turds that usually contain color commentary from people working too late into the night.
What do I like? Use long, descriptive variable names; solve problems with the simplest approach possible; separate the problem into layers; etc., etc.
And generating code from comments? Please... for that to ever really work, the comment syntact has to be as strict as code!
When you need a comment, it's usually a sign that the code is not clear enough. There are very few cases where the code can't be rewritten in such a way that a) the code is better, and b) the comment is unnecessary.
Most of the cases where that's impossible are commenting things that should not happen. Those comments are valuable.
Comments that discuss the design are generally better served by separate design documentation in a human-readable format, with diagrams.
Out of date comments are far far worse than none, and this happens with absolute certainty.
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.
Servlet v2.4 container in a single 161KB jar file ? Try Winstone
. India has more engineers than the USA. And these are smart people.
Smart, but lack the institutional knowledge of why comments are good for you. They'll make the same mistakes that the US has gone through for the past dozen years.
Having RTFA, I can see what he's trying to get at, but as someone who has (unfortunately) found himself spending most of my 10 year career in programming cleaning up other people's poop. At first I thought it was because I must have done something wrong that I kept ending up being assigned this work, but as I came to realise, it was because I make the code better than I found it and I have a knack for fixing stuff other people give up on. I also had silly managers who assign work to the people least qualified to do it.
At any rate, some observations:
1. 20 lines of comments "documenting" your code before you write it (or even after you write it) is far less useful than writing the code COHERENTLY and CORRECTLY in the first place.
Last month, I had a 1200 (yes 1,200) line method with huge blocks of documentation before big pieces of code. I still can't quite tell you what it thought it was doing. The code was a for loop wrapping around code to handle 3 different and mutually exclusive situations. Instead of identifying which of the 3 situations it was and creating a method for each situation, the person just stuffed it all in with lots of comments documenting everything the article's author said. The code was still unmaintainable.
2. Comments are useless unless they are kept up to date
Part of the reason that code was so difficult to figure out was because most of those big verbose documentation comments referred to a completely different implementation. After the programmer had written the first case, she encountered some other bad cases and eventually had to completely change a block of code embedded in this 1200 line for-loop. The code was now correct, but the comments no longer had anything to do with that block of code.
3. Don't be clever when you can be clear
I have made a solemn vow to hunt down and hurt anyone who puts "clever" code in my project. I am so sick of trying to figure out what some obfuscated piece of code in C, C++ or even SmallTalk is doing. And find out it was just a "clever" way of doing something pretty straight forward like iterating over a list. There was no speed gain from the clever trick, and the code wasn't even a bottleneck to begin with. *sigh*
4. If you don't know how to solve the problem, write some experiment code in a separate app to figure it out. Then take the time to do the "right" thing in the production code.
3 days from final for a video game. The CD streaming library for the Sony Playstation was making this strange "hic-up" sound at rare moments. By this time, the original author of this code has long since gone to another company. So I plunge into the code and found that the original programmer didn't know how to write streaming code so he created this hack of a hack of a hack of a test (ad nauseum). The code was programmed by accident, not design. No amount of comment before coding could help this. If the author had dumped the code, wrote documentation describing everything he learned then wrote the code, things would have been a lot better.
5. Unrelated to comments, but use variable names that make sense. Don't name them arbitrarily or to amuse yourself!
That CD sound streamer code I mentioned above used quirky names for variables. Can you tell what "little_ninja" is supposed to be just from the name? When I confronted the coder about this quirk of his (in another library he wrote), he got all huffy and didn't understand why people didn't appreciate his little puzzles or his sense of humor. It galls me he still earns a paycheck in the industry.
The bitter lessons of a veteran coder: http://bitterprogrammer.blogspot.com
Where's plausible deniability when I need it?
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.
I originally thought you said MDMA... in which case, sure! That solves everything.
XML is like violence. If it doesn't solve the problem, use more.
Parent's views are stinking with prejudice and don't deserve any postive mod points.
Parent is a racial bigot, okay??!!??!
And BTW, I am American with no direct Asian ancestry... Not sure I want to be proud to call parent American though.
One should start by writing the documentation for classes and interfaces, including for properties and methods. Then, one should write procedural pseudocode in english (or similar language) for the body of each method, as comments. The final step should be to write the corresponding Java code below the pseudocode. The biggest issue with that approach is documentation maintenance, which requires a great deal of discipline. But as they say, garbage in, garbage out.
program.files.each do | class |
class.methods.sort.each do | method |
5.times { method.refactor! unless method.elegant? }
end
if problem_domain > current_language
choices << comp.lang.each
current_language = choices.best
project.restart
evangelise(current_language)
end
end
comments << intentions.remove(implimentation_details)
puts comments
def refactor!
method.split! unless method.size < Too_Big
method.rename! unless method.name.clear?
end
def evangelise(lang)
slashdot.comment.post
puts "#{lang} is the only real language"
end
goto (1.0/0.0) and $beyond
http://www.rubygarden.org/ruby?MoviesTheRubyWay
A lot of people, myself included at one time, rightfully concluded the _particular_ people going on about comments were at best misguided, or at worst looking to fire people.
That said my own opinions have progressed (regressed?) a bit. I make no claim that any of this will work in the face of grossly incompetent developers, but neither will anything else. Furthermore I'm only talking about comments/documentation for internal consumption, not about API docs or header comments or anything else like that.
Lots of code is effectively self-documenting. There are a great number of self-explanatory idioms that any competent programmer should immediately recognize. These will vary from place to place, but there are basic ones like iteration and recursion, swapping variables, and so on that just don't need commenting in and of themselves. One exception to this is to make up for a language deficiency. For example when writing java (ugh 1.4) I always put a comment next to a Collection declaration saying what exactly it's a collection of.
The more interesting and important comments are algorithmic comments. Any time I implement a non-trivial class, I try to write up a full semi-formal description of any non-trivial algorithms implemented. Then I use that as an effective specification for implementing the actual code. The point is at least two-fold, to get myself to really comprehensively think about all the cases that need to be dealt with, and so when in the future I can figure out what the code is supposed to be doing. Obviously some discipline is required. I find it helpful to not think of keeping comments up to date with the code, but rather keeping the code up to date with the comments. Although I am not directly familiar with any literate programming tools, from what I've read it seems like it's a more formalized version of this approach.
The programming process involves significant meta-data which is not in the actual code. This is what needs to be commented. Code does an excellent job of telling you what is being done and how it's being done, but only comments can tell you why the programmer thought it was a good idea at the time, and what the programmer thought it should be doing.
Or the converse: they turn out reams of repetitive documentation, but you still can't make sense of the code. I've seen this first-hand, and it's monstrously frustrating.
Well, that assumes that you have a nice, clear set of steps (like the example above). However, if you have a series of very complicated, non-intuitive steps that MUST be done, then commenting is pretty much essential.
XML is like violence. If it doesn't solve the problem, use more.
I talked with a programmer who's been in the buisness for a while. He claims, long variable names, and functions that say what they do is more important than comments.
He goes on to say that as you change the code, and forget to change the comments problems arise. But if you make your code readable, then you almost don't need comments.
God spoke to me.
This guy *loves* Donald Knuth's literate programming. So does our UW Quantum System Engineering (QSE) Group ... we call it "Literate System Engineering".
However, upon consulting the INSPEC database of academic abstracts, 1955 to 2005, we find:
Containing the word "Programming": 124252 abstracts
Containing "Literate Programming": 81 abstracts
So the harsh truth is, only a tiny fraction (1/1500) of academic software projects mention it.
How many (if any) SlashDotters use Literate Programming regularly?
Pretty much any Indian with the education to program spoke english before they programmed.
Many (i.e. millions) of Indians speak Egnlish natively. English is a global language and just because Indian English does not always soudn the same as American does not mean they cannot speak English.
I have to admit that often times my Indian peers at school know the language better than I do.
http://en.wikipedia.org/wiki/Languages_of_India/ http://timesofindia.indiatimes.com/articleshow/55You've just described how the folks who program the Space Shuttle's computers code. Unfortunately, convincing management of the wisdom of this approach will be difficult.
Of course, there are a lot of things that programmers can do to make code easy to read, but I'm quite interested in the things that computers can do to make code easy to read.
For example lxr.linux.no is great but it would be even better if it was integrated into the editor. They say etags is the same, but I've never been able to make it work.
Another thing that would be great would be color coding for bugginess. There are a bunch of different static analysis tools that could generate a bugginess value for each line of code. Also really picky indent color coding would be nice.
Another thing would be better integration with the CVS. Something like this perhaps. It would be handy to know if a bug only affected 2.6 or if it went back to 2.4 as well.
Those are some ideas. Gotto run.
In "Literate Programming" the comments are all important and the code itself is trivialized. The code, as Jef told me, is like "raisons in the muffin of the comments." There are paragraphs of verbiage which might go on about the history of the project, why certain features were discarded, etc., etc, and might not even explain what the following line or two of code was concerned with.
It's really very difficult to deal with code that has been written in this style ("literatized?" ) since the actual structure of the program is severly obscured. It serves as an example of how overdoing a good thing is usually a bad thing.
Jef was a nice guy, and I recommend his book, "The Humane Interface" for its many interesting ideas. His attempt to put them into practice in the Archy project http://rchi.raskincenter.org/aboutrchi/index.php/, was not completed before his death. Even for that, Archy is very close to his vision.
But since Jef was in many ways an extremist, one can demonstrate in Archy his pushing of his concepts to the limit resulted in the end fully maching his goals. Somewhat like "Literate Programming", in fact.
I think that BOTH the comments and the code need to be readable. I've seen code with lots of great descriptive comments, but when you look at the actual code you can't tell if it does what the comments say it's supposed to do. The same holds true for the reverse. I've see code that's well structed, readable, descriptive variable names, etc. But without some comments about how all the pieces fit together the code can still be confusing.
For any non-trivial software system you need comments AND meaningful names.
I found that while meaningful names are useful to describe how program works in terms of a language, comments are needed for a proper mapping to a domain area.
I found commenting conditionals and switch bracnhes particularly useful - in a comment I explain for which situation in a problem domain that was done.
I also find very useful to put problem-tracking references (like PR31337) useful, when I need to fix some problem report or implement a small feature. Later, that _will_ help you to understand WTF this kludgy code does. It even may save your butt if you are stupid (or inexperienced) enough not to have unit and regression tests.
my sstream of consciousness
The true useful skill lies in reading sloppy and/or wizardly code. Some people think that they have job security if they write impenetrable code, but then they can just be fired and all their code rewritten. If you can read others' "unmaintainable" code, you enable your employer to save money by not having to rewrite everything the guy they just fired wrote. So they'll want to keep you around as they fire/downsize everyone else. I It doesn't really matter what kind of code you write, since you can read whatever. advise everyone to start reading up on the Obfuscated C Contest, and practice figuring out what evertyhing does. Then you can handle any kind of code thrown at you, and the code you actually write becomes of secondary importance.
short, descriptive variable names
Sounds like an oxymoron to me.
With cut-and-paste and modern editors, there is little reason for short variable names.
Structure is more important than documentation because you can't document something that doesn't make sense, and even if you could you wouldn't know where to put the comments. In a well structured program each section (not each line - that's overkill) will have a clearly defined purpose and comments will be easy to write.
I often don't like the choices people make, but I like the fact that people make choices. That's why I'm a conservative.
It's not out of laziness, I just don't have the mental capacity to be able to stop and thoroughly comment and also maintain that mental picture. Ideally I would go back later and comment what I've done, but of course what happens in practice is that I continue on with the project. Yes this causes me to have poorly commented code. And as usually I'm the only audience for my code, I'm the one who suffers for it later. But I don't have a good answer. I'm not making excuses for not commenting well, I'm trying to explain why, for me at least, code tends to be poorly commented.
/. needs to cut back on the rampant cultural stereotyping. I fail to see how Indians are innately less intelligent, or would make lesser engineers than their American counterparts, simple because they are Indian. And might I add that a large reason India is so useful for outsourcing is, as a former British Colony, it has sizeable English speaking populous. The Indians I know speak English very well, and their language construction is better than many Westerners. Just try to get used to the accent. Which is somewhat less chanllenging with comments in code...
Definitely not. No matter how clear your code is, it only gives you an idea of what is going on the small scale. You often need comments to describe your big-picture motivation. But the comments have to be good too.
Here's a classic bad comment:That's useless. But a comment can help:No matter how clear you write the code you're not going to get that much understanding without a comment.
It's just a simple example off the top of my head, but that's how I use comments. The code clarity is all that's needed to tell what you are doing, but comments can tell you why you are doing it. You need both for truly maintainable code.
Cheers.
Unit tests and small, well-defined classes resulting from TDD have done more for me in understanding very complex systems than comments in poorly conceived or over engineered code.
Writing clear code in the first place is your best option. If the code is concise and well written it is easy to understand and an joy to work with. Of course there are always instances where something requires a tight loop or you're interfacing with an external API that is not consistent with the calling code. In these cases you need comments. Use your head. Don't comment or not comment as some kind of religion. If the code is hairly comment it. If the code is obvious don't comment it (and not because you don't have to - it's an annoying distraction to read useless comments).
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.
My learning experience about commenting code was a difficult one. Like many, while in college I wrote the code and then went back to comment it so the profs were happy.
Then I did a co-op with an automated storage/retreival systems company in their software department. One of the processes involved in a communications system needed some work. The code was licensed from another company in another country. There was no documentation for this communications system. There was very little commenting in the code. Luckily it wasn't in a foreign language. Unluckily it was wrong, apparently the structure of this program was similar to that of another, which was mostly gutted and rewritten, but a few old-program comments survived to be the ONLY comments in the new program.
Sure, the sources could be reverse engineered to provide the documentation required. I did it. It took a few weeks.
After that, I didn't leave comments for last anymore. It's been a good thing. I now work for a semiconductor design company and often write perl scripts or skill-language scripts to automate tedious tasks. I think I'm abou thte only one in the office that comments such scripts in any way. It's nice to read what stuff does when I have to revisit code many months or years later. I hate having to revisit someone else's code because it's nearly guaranteed to be completely barren of anything human-readable.
Listen up kids! Commenting is GOOD! Your professors aren't just being jerks. Learn the easy way and hopefully save yourself a great deal of trouble with your own code. Other people's code will always suck, but your own shouldn't have to.
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.
Your colleagues are idiots.
How To Write Unmaintainable Code
;p
In the interests of creating employment opportunities in the Java programming field, I am passing on these tips from the masters on how to write code that is so difficult to maintain, that the people who come after you will take years to make even the simplest changes. Further, if you follow all these rules religiously, you will even guarantee yourself a lifetime of employment, since no one but you has a hope in hell of maintaining the code. Then again, if you followed all these rules religiously, even you wouldn't be able to maintain the code!
You don't want to overdo this. Your code should not look hopelessly unmaintainable, just be that way. Otherwise it stands the risk of being rewritten or refactored.
i read this article a few years ago and personally found it interesting. as i bolded out, documentation is important even for yourself. it depends on your motive for or for not including good comments for your code. if you're on a team, good comments helps speed up the project. if anyone else will be reading your code and using it, i think it's personally quite important to leave comments especially on what the function does and how to use it.
on the other hand, as this article states, if you really really want to keep your job... then useful comments are totally unnecessary for that'll only help the guy that's coming along to replace you.
HD Trailers
Right. When XP-heads tell you not to comment your code because it's not Xtreme, tell them they're wrong.
Now, how I handle the indent issue (if tabs are involved) is:Then, just M-t every time you want to change the tab spacing, so that it matches the indentation of whoever last edited that section of the file.
one hundred twenty
is just enough characters
to write a haiku
Your links don't seem to work. (Hint: not all URLs need trailing slashes...)
Even in a language that is supposedly "self-documenting" like ObjC just from the naming conventions, I find that it's much easier to work with the code if about 20% of the lines in the codebase are comments (including those in header files).
Many times comments are out of date.
The code tells me exactly what is going on.
Why are we keeping source code and comments in the same file? What would be nice, would be a editor that keeps them in 2 different files, say, file.c and file.cmt or such such, but when you want, with a single keystroke toggle, superimposes the comments in your source. The comment file format would need some metadata, to show where it should appear, I'd think.
I had a co-worker who needed a little help with his program. It was C code, but all the semicolons were in column 80, arranged in a nice column. Yikes. He casually said "what, you've never seen that?". Turns out that part of his problem was that he was using float to represent a byte position in an extremely large file. He knew enough that UINT32 wouldn't do it, but ...
HIV Crosses Species Barrier... into Muppets
Short variables should be enough? Maybe, let's look at some sample code:
p_var = party
b_var = beer
c_var = coolers
.
.
10,000 lines of code later:
.
.
p_var = b_var + c_var
It will make perfect sense, no?
My wife doesn't listen to me either...
whose name escapes me at the moment. But the idea is that you write comments that are like "psuedo-code" but much more English-like than ordinary psuedo-code. Then you refine the comments down further and further until you replace the lowest-level comments with individual statements, and the higher-level comments stay in as documentation. I remember trying this once and, while overkill for the simple project I was doing, I wrote some damn fine (and readable!) code that way.
If it's not one thing it's your mother.
as a full-time student who worked part time during summmers coding a php/mysql/flash based website... i know exactly how important comments can be. last summer, i'd have to go back to code i wrote the year before in order to update it or something along those lines, and i'd stare at it for hours thinking... "wtf is the point of this? i know it has some point, but i can't put my finger on it!" since then, although i have done very little as i was replaced by an immigrant from india... (grrr).. i have pledged to make decent comments in my code that detail what in god's name is going on.
What is worse than a lack of comments? useless/redundant comments!
// store penis size
// store average martian penis size for later comparison with human penis size
final int iPENISSIZE;
well no shit sherlock!
What I'm getting at is very basic and it's no secret to us. Our goal is to write code that will make a coder understand what the system has to do regardless of who looks at it(programmers obviously.., not martha stewart and when. If that can be achieved, than I think that the programmer who originally wrote the code did his job right.
My beef with this part of programming is the following. I'm in my 2nd year in computer science and what was common is when the teacher asks for commented code, students would put obvious comments (commenting things that are self-explanatory) because we're naturally lazy (I fucking am) but this is IMO a bad habit because you just read things that aren't helping you and what you want is help/clarification! Something like
final int iPENISSIZE;
We just recently started writing GUIs in Java. Because the GUI part makes our program bigger and the code longer, organization within the classes became more important than when we didn't do GUI's so I was thankful that I wrote comments before even started coding as the programs became bigger because it saved me a shitload of time.
I think the teachers should try to get the students on the right track and make them get "good" habits to later not get b0rked when things become more complex.
I recently read the Jack Reeves article What is Software Design?. His thesis, really, is that the code is the design. I didn't really want to accept this at first, but I do see that there are some benefits to looking at it this way. In fact, I think that if one were to take this to heart while coding, the result will be better, more intelligible and maintainable code.
Quality comments are one aspect of this (and I think that javadoc, for instance is a great tool). But just as the code isn't static, the comments need to also get updated, and it's fairly easy to refactor a method and forget to update/redo the comments.
Another thing I don't usually see enough is coding to actually check whether input parameters are valid, or otherwise enforcing the "contract" between a class/method and it's caller. Simple, basic stuff, but I know what happens when fatigue set in and people are hurrying to meet deadlines.
All one has to do is hit the right keys at the right time and the instrument plays itself. - Johann Sebastian Bach
I worked for a great little company named SofTech many years ago, where we developed an analysis and design methodology named SADT (aka IDEF-0). One of the important parts of it was a set of steps to make sure that the documents being produced were readable and understandable, under the philosophy that something that was correct but impossible to understand was a lot less useful that something that was wrong and understandable. For the latter, you could tell it was wrong and figure out how to make it correct.
It's always seemed to me that this is one of the major parts missing from Open Source. Note that this makes moot the question of whether you make it understandable by writing lots of comments or by using a good programming language; either one will pass the test.
1. Comment each function
- 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.
Somewhere in a perl book I came across a comment that said:
"It works just like you would expect it to, however it is hard for us to write how you think"
Should tell the reader what the code should do, not simply describe what it does do.
Code comments on you!
sigfault. core dumped.
The ultimate acid test for documentation:
/* compute sin(x) to 50 significant digits using Taylor Series approximation */
1) Is the documented code clearer than undocumented code?
2) Is it plain to the naked eye that the person could've made the code significanty clearer by having more, less, or different documentation?
Self-contained routines may need little or no internal documenation. Even a multi-page algorithm to do a specific function, like compute sin(x) to 50 significant digits in the days before floating point processors were common, may only need a one-line comment before the code if the variable names are carefully chosen and the code is easy to follow:
On the other hand, some 4-liners need 800 lines of description to comprehend, particularly anything from this web site.
Knowledge is how to play a game, intelligence is how to win, wisdom is knowing what game to play.
Descriptive variable and function names and well organized code can only do so much. Someone still has to understand how that organization scheme came to be and what the relationships are between all those variables and functions. That's where comments come in handy.
They can tell the reader the bigger picture; the reasons behind certain decisions, what relates to what and how things should work. The code itself describes the specifics of how things are done. Comments describe a general overview of the how, and more importantly, why they are done that way.
+1 Insightful, -1 Troll. What can I say, I'm an Insightful Troll.
More to the point, people need to put some value into their comments. "i++" commented as "increment i" is worthless; commented as "set foo pointer for next bar compare" might have some value.
Do not mock my vision of impractical footwear
While there may be an argument for either case, I think there is no one clear-cut-absolutely-definitive-all-encompassing case.
I've come in on a project that had the following functions barf() and snarf() with oodles of documentation and not one single byte of source file was of any use to me because quite frankly it was so horribly designed that even with a hunting dog and ouija board, I still couldn't make sense of it. If I remember correctly it took me about 2 or 3 weeks to finally figure what that particular section of the code did. barf and snarf? Who the hell thought barf and snarf were acceptable function names?
I've seen an entire project written with every single function documented with the following: PURPOSE, USAGE, INPUT, OUTPUT and a bunch of other stuff, and about half of it was simply wrong because while it started off well enough, as the project matured and the nature of the functions changed, that documentation was poorly maintained to reflect those changes. Over time there becomes a chasm separating the actual behaviour of the code and the intended behaviour that is documented or started off as being documented.
On the other hand, I've seen projects that were very easy to follow because the team who maintained it wasn't afraid to type in 20 character long variable names that actually meant something - specifically meant what it represented.
I'm currently developing a java based application for my boss and one such group of functions ensures the double variable used to maintain currency remains as proper currency, so I wrote a simple class to reformat the value of the double to a proper currency format. That class is called 'CurrencyFormat' and has format() and toString().
Seeing as how I've based it on several other classes found in the standard java API, anyone who knows java should be able to figure out quickly enough what
invoice.currentSubTotal = 0.0;
for (int i = 0;i < invoice.lineItems.length;i ++)
invoice.currentSubtotal = CurrencyFormat.format(invoice.currentSubtotal + (invoice.lineItems[i].quantity * invoice.lineItems[i].value));
does. I've looked at code I wrote 5 even 10 years ago and while I get the sickening feeling of 'what the hell was I smoking when I wrote this damn stuff', I've never had a more than the very brief problem of trying to decipher what the code actually did because my boss at that time insisted I use meaningful names for functions and variables..
In my experience, while code and documentation might start off alike, during the course of an ongoing project, documentation - especially maintained by someone other than the original author of the block of code - will either be incorrectly maintained or will not be maintained at all. Sometimes it might not be a bad thing, sometimes the change can be so major that anyone who then relies on that documentation will go on for some time thinking that's what it does when in fact that is NOT what it does.
My experience tells me that poorly maintained CODE documentation can be more detremental than no documentation at all. However, its probably important to have a proper PROJECT design AND documentation overview. For example, no reasonable project should have all source files in a single directory and even then it should be more than arbitrary. A good layout and set of rules as to what goes where is as effective as a chapter of docuemtation. I have a 'db' directory for classes that deal with the database and a 'lib' directory for simple library like classes and a 'ui' directory which also contains ui/lib and ui/dialogs and ui/reports, etc. It should not be unreasonable if not redundant to maintain a project level document to say lib/QSort is a quicksort class or ui/dialogs/About is the about box. In the course of the projects lifetime a 'project bible' describing the breakdown of the project in those terms (Any modal dialog box that displays information and/or prompts the user for information or for a response goes in the ui/dialogs directory), etc, should e
GRANDPARENT: Especially if you change the code and now the comments are wrong
PARENT: 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...
PARENT: As Fred Brooks said, "There is no silver bullet."
A database backend would go a long ways towards providing a silver bullet, i.e. if instead of writing your code to an ASCII text file, you were writing to a document management system that kept doubly linked associations between the lines of code and the comments associated with those lines of code, and if code/comment pairs had dirty bits, so that if you changed one [e.g. the code], then the dirty bit wouldn't get changed to clean until you verified that the other [e.g. the comment] was correct, then that would go a long way towards solving the problem.
I think we are still in the infancy of code/documentation/database integration, however.
good code = little commentst ml is a great model of how to write comments
http://www.lysator.liu.se/c/pikestyle.h
I'd suggest reading code from old unix sources, or plan9, or any program written by good programmers and you'll see that you have something when comments are almost gone.
Something even more scary about India is when executing long term projects that require large amounts of domain knowledge. Indian programmers are jumping from job to job just like we did here in he late nineties. Typical time stayed at one company is less than two years.
Our offshore (India) support team has had 100% turnover in the last year. When it takes at least six months for a typical developer to have enough domain knowledge to be useful it means that we have a large number of very cheap very junior developers to tell what to do. And sadly, telling them what to do usually takes just about as long as doing it myself.
I am not a script!
No one with any experience in maintaining a system of reasonable complexity could sanely argue that good comments aren't of benefit during maintenance.
I've worked at dozens of businesses as a consultant over the past few years. Lack of comments is *always* a give away that I've just walked into a bucket shop. Then the sinking feeling starts. Comment free code is often accompanied by the usual suspects:
I've seen this so often it's like Groundhog Day! It's particularly inexcusable if the developers have some experience of maintaining their own code. Perhaps their egos get in the way of critically analysing how they could do a better job. In development, arrogance is the brother of mediocrity.
One of these days I'm moving to Theory - everything works there
It's fun to hack away at home on personal projects, but professional efforts - especially big ones - really do require decent documentation and comments in the code.
Unfortunately my experience is that the requirements documents, design documents, and even the comments in the code are usually out of step with where the code actually is at a given time.
I've seen a lot of code written by the local genius that only that same local genius can maintain. That's not doing anyone any good.
How many times have you looked at a chunk of code and thought it'd be easier just to re-write it than spend the time understanding what's there in order to modify it?
Long story short, my vote is for well documented, well commented code. And keep it simple too. Unless you're under contraints that require you to get creative, just write it in a way that others will understand.
self documenting code. It has to be said, and hammered and said, and hammered.
The fact is that code is an implementation of a design's ideas and as a translation of those ideas it can misinterpret or even be erroneous. The idea of commenting code is to state what the intention of the code is (and hopefully there is a design document to back that up as well). And incase anyone doesn't get the point of that it's called comprehension and verification.
I won't bother as to why people tend to not do this and why it usually adds massive maintenance costs and simply blows chunks wrt. quality....grrrr.
Think I'll go toss some ice on that nerve...
If it was hard to write, it should be hard to read.
Steve's Computer Service, Hobbs, NM
What should be done is: Take this 1000 line programme. Add on 5 lines. Add on 20 lines. Add on 100 lines.
Hear hear!
Although, I think it should be 10K lines. Of poorly commented code. And it should be real, honest to god code; grab it from some department or other. Most (I would imagine *ALL*) engineering departments have a number of 'small' codes that do useful things.
If aerospace FORTRAN codes from the mid 70s don't teach a code-monkey-to-be WHY the goto statement should at LEAST be well commented (if it must be used at all), *NOTHING* will.
If the comments don't match the code, they're probably both wrong.
The other thing about comments is that they can be funny. I remember a couple of bugs we tracked down where a failed hardware access resulted in an infinite loop. Sure enough, when we dug in to the code, that while() loop had a comment before it along the lines of
/* i should probably put a guard counter here */
Heh. And then I think of the pain and expense those bugs caused.
I'm just saying that they (usually) operate under a different set of assumptions and priorities. If you're writing shit someone else (in the US) will have to support, then why bother with proper coding standards, refactoring and comments?
So far the code I've seen come from India has been ATROCIOUS. This is not to say that US programmers can't write atrocious code, but those who do usually get kicked out pretty quickly.
I opened his listing (printed on non-recycled 11x14 paper), and was surprised to find the listing double-spaced. I tried to figure out how he did it (assuming it was an obscure parameter on the job control card), and eventually realized that he had inserted a blank comment between every line of code (ignore and forgive the periods; I had trouble indenting):
Understand that this meant that, while at the keypunch, he took the time to type a single "C", then feed a new card (taking a couple of seconds), before entering another line of code. (Not to mention the waste of expensive card stock.)
When I asked why he took the time to generate all those blank cards, he answered, sincerely, (wait for it...):
"The professor said the program would be easier to debug if we had a lot of comments."
I've worked with plenty of N. Americans who've done this c&p crap. Indians don't seem any worse. Perhaps you've had a bad experience, or are just a bigot.
Having recently worked though a 40 Kb cgi script (agora cart) with about a quarter Mb of libraries trying to make a few changes, I can safely say I would have rather had a lot more comments rather than the descriptive variable names in the program. Of course, descriptive variable names should be used with the good comments for maximum understandability.
what sig?
and they feel that theirs is the definitive solution to the question at hand; is commenting more useful than well organized coding arrangements? In my novice experience with computers and various languages, I have realized that the most important element of handling someone elses' code is the ability to decipher their structure and intent. Sometimes good commenting helps, but in the long run, commenting can also impede the visual flow of my 'reading' the code, and make it more difficult to properly grok. Ultimately, when I handle another person's code, I am more grateful for well structured and defined blocks of code than silly comments that usually just tell me what I can read for myself. Granted, more complex blocks of code make this a bit more work, but I just print out hard copies of that section of code, and use highlighters and reference pointers to think about what the original programmer was doing, and then I usually discover the solution, while simultaneously having a better understanding of how that person's mind works. After handling 7 or 8 pieces of code this way, I can understand the programmer's coding better, which is a lot better than stating the obvious, which is what *most* commenting really is. I'm no super guru, and I leave my experience and interpretation of my work up to the community, but in regards to the original post, this is my opinion and justification of such, which is all I am capable of providing.
Last time I checked, code does shit. Comments don't.
ever try to gcc your comments and run the executable?
__________________________________________
Take comfort in your ignorance.
Grandmaster Plague
I have written programs in both raw and literate programming style, i prefer the latter. In fact, i wrote a literate-program pre-processor to write programs, and it made the program easier to write and more bug-free.
In literate programming, you rely on a pre-processor to make the output production, so you are free to put things together as you want. What this means, is that bracketing code (eg open, close files), can be written in the same block, which are invoked separately.
The main program then ends up looking like a rough scetch, full of commands to include other bits. With wing comments, it is easy to see what is going on.
One uses a folding editor to search for strings like "!topic". This will not show you a consolidated index, but you can use it to also show where you're are, and any missing bugs.
On the main, Jon Bentley's comments on Literate Programming are fair (that is, it creates a good environment for writing single-purpose code), but one needs to consider the context the program is written for.
The form i use was specifically designed to allow all sorts of text-output, so the same file can make as output, eg .CMD, .REX, .TXT and .HTM output, which means that when you run the script you get a perfectly matched set of files, all correctly pointing to each other.
OS/2 - because choice is a terrible thing to waste.
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
John F. Woods
A professor teaching operating systems had everyone modify sys_fork(), the proc struct, sys_read(), and sys_write() in the linux kernel (using UML) to implement a filtering mechanism and to write a loadable kernel module to install and remove the new functions (the proc stuct had the filter field independent of the LKM). Nearly everyone in the class got the assignment correct, using packetstorm and google as documentation.
Only problem? Grading it was a pain in the ass.
Recently, I've been developing a massive website with PHP-Nuke, and I've been modifying all of its modules extensively. Although the functions and variable names are self-documenting, since PHP is not a strongly typed language it is often difficult to see what a function accepts as a parameter and returns just by looking at its definition. I would have vastly preferred it if the developers had commented it.
At our school, we don't earn a degree when we graduate—we earn pi/180 radians
If BSOD
then
do.reboot
'When are we going to offer users
'the ability to change the color?
else
do.eat "\Device\RAM\ALL DIMMS"
'Damn this is some bloated shit
end If
Don't let your ego screw other programmers over. Everybody thinks that they write clear, logically-flowing code whose meaning is self-evident.
Sorry, but your thinking about code doesn't correlate with my thinking about code and as the submitter pointed out, his own thinking about code doesn't even correlate with what he was thinking 3 years ago.
The fact of the matter is that most people can hold about 7 items in their head at one time and those 7 items add up fast when you're dealing with code.
At the very least, write a summary for the class/structure and summaries for the methods. Even if methods are small (as they should be), most of the time people don't care about the internal; they just want to know what it does, pre-conditions, post-conditions, and any other caveats.
Even if code was written in English, it still would necessitate summaries. Think of code-folding in your editor and how you only want to look at what you're interested in.
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
I can't believe noone has posted about this yet. Click here (or check /usr/src/linux/Documentation/CodingStyle) for Linus' witty and insightful views on this topic. Chapter 5 in particular.
Raj Against the Machine! http://social-butterfly.appspot.com/
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
Slashdot comments are more important than....... uh, I can't think of anything right now. Anyone?
English lets you to articulate the nuances of the code that might be missed in the harsh structured environment of Java. Comments allow you to draw outside the lines!
I see several responses questioning the reliability of comments. Code can have bugs, why not comments? If the code has a bug I fix it. If a comment isn't "right", I fix it too. Just as you should look at all code with a bit of suspicion, do the same for comments.
Sure, programmers can and do write bad comments -- and they're probably the ones that write bad code. We all grow. I no longer write one comment on each line of assembly code but instead use a paragraph or two to describe a section of C++ code.
Writing self-documenting code is nice, but have you ever tried to interpret uncommented, templated C++ code? It isn't pretty. Thank goodness we have debuggers that will step through the layers and layers of indirection to finally get you to an invocation of some real code!
Code is useful for describing what you are doing. Comments are for explaing why (e.g. "I'm calling the xxxx routine because there is a bug in the .NET framework v1.2 which will hopefully be fixed in the next version but this call should work in either case.")
Weinberg wrote a book with that exact title.
The problem is that each progammer approaches coding in his unique way. There are an infinite number of solutions to all but the most trivial programs.
I'm constantly saying to myself "Why did he write it this way?".
Comments raise the abstraction level just like patterns and higher-level languages in general.
So until we all become Borg, we're going to need comments
What inputs are acceptable. What inputs should be rejected. What inputs lead to undefined results. What guarantees do you make about the outputs.
A function makes a contract with the outside world. Make the contract clear. Then add assertions. Good assertions are often better than good comments anyway.
Imho comments are for people who can't read code or just write sphagetti code in the first place. I always say my code is my comment, because it is good and clear enough to understand, without littering it with silly comments.
Btw my experience with comments are half of the time they don't match the code! They comment and then update the code, again and again and again and the code doesn't even match what they said it did.
If you really want others to understand your code write a design document to give them an idea of what your code is supposed to do. They can figure out the rest from the code.
did you forget to take your meds?
I just wrote a piece of code and commented it properly. I used Doxygen style comments.
The beautiful output documentation produced by Doxygen automatically was worth the little extra time spent on commenting my code.
~Aha~
I love telling this story...
// break
Last year I had a brief stint at a small software company that had just taken a project in-house that was developed by an outside contractor. My job was to take the code they'd just inherited (which no one there knew anything about) and add some features to it on a tight schedule. Documentation? What documentation?
The extent of all of the code comments it had was the following (and no, I'm not making this up):
if(...) {
break;
}
If that wasn't bad enough, I knew the original developer personally. She was a former professor of mine and I'd worked for her company only a few months before she had taken that contract.
As someone who has had to deal with code with descriptive names and no comments or docs to go with them: If you write such code, may you rot in the lowest level of hell along with traitors, used car salesmen, and people who answer cell phones during movies.
--GrouchoMarx
Card-carrying member of the EFF, FSF, and ACLU. Are you?
No joke, that was in production code from developer that I'm sure a lot of you would recognize. There was also something in there to the effect of:
But I didn't find that one, I just heard stories.
Nick
Type I
Developers that spend all day complaining that all they code they have to work on doesn't have enough comments and how everyone needs to stop coding and write detailed design documents.
Type II
Developers that actually implement all of the functionality while ignoring the complaints of Type I developers.
I think it's safe to say comments are for the benefit of those who have not assimilated their language, their APIs, etc. Sure, documenting interfaces is essential as well as how certain data structures are used. Most of the other comments I have seen are completely superfluous and only enhance the understanding of the uninitiated.
cat
... his pictures. managers need commented code because they can't read them.
I think it's safe to say comments are for the benefit of those who have not assimilated their language, their APIs, etc. Sure, documenting interfaces is essential as well as how certain data structures are used as well as how certain events can interact.
Conversely though, most of the other comments I have seen are completely superfluous and only enhance the understanding of the uninitiated.
cat
only comment those functions which are difficult to understand.
And generally, if you use proper names for variables and functions, you won't need commenting for simple functions.
Also forgive me if my syntax is rusty, it's been a long time (thankfully) since i touched that stuff.
Comments, at ***BEST***, tell you what the author of the comment *hopes* was going on, at the time it was written. The code that follows may well not do anything of the sort; it may have, at one point, only to have been re-written by somebody else at a later date; it may still do what was stated, though that's no longer what's needed.
;)
Yes, it takes longer, trying to grok uncommented spaghetti code, but doing so on a regular basis will help you develop a reputation for being able to fix any bug, anywhere, any time. It even allowed me to track down a bug in a now-defunct version of Borland C's optimizer, that produced incorrect code when two seemingly unrelated options were selected. There ain't *NO* amount of commenting in the source code that would have helped there.
Learn to do your job right. Don't depend on what was written in any comments. The compiler ignores comments; so should you. However, as damned few programmers actually know how to debug other people's code, and many are too lazy to read it like a compiler, do add comments to your own code. It makes the stuff easier for PHBs to read.
For those who want to grok code the way it's executed, I'd suggest you start like I did, by reading old obfuscated C code winners, and running them in your head, comparing what you got with what the computer got. You'll burn up a lot of scatch paper, but eventually, you'll see what I mean.
Lemon curry?
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.
Comments may be important, but not quite as important as well-written, organized, and coherent code, with well-chosen names for functions, variables, and types. When a program is written in such a way that it's obvious what it does, so you can read it and understand it, the comments might just have to describe why things are done a certain way. In most code, 90% of the stuff is obvious, boilerplate, exists-in-every-program kind of stuff anyway... It's that 10% of code where the real logic of a program happens where you need to make sure that you comment everything so well that there's no screwing up.
I think this comes close, but just misses pointing out a few things that are salient here: 1) comments need to be tailored to the audience and the intent of the code. If you're posting code to alt.comp.lang.learn.c-c++ (for one example) it's perfectly resonable to write a lot of comments that would be downright insulting under normal circumstances. 2) Short of getting ridiculous, self-documenting code only documents what it does, not WHY it does that. Comments should usually tell why. 3) IMO, the comment elsethread about commenting interfaces started out well, but then went astray. Commenting an interface is a good thing -- but you should NOT have to tell what the interface does, because if comments contribute to that, the interface has serious problems that need to be fixed. Variable names are the least of writing self-documenting code; good function names and (where applicable) class names are far more important -- the interface itself should make its intent obvious. Comments on an interface _should_ be used to tell about those things that can't (reasonably) be made apparent otherwise, such as preconditions and limitations on the interface.
The universe is a figment of its own imagination.
I'm very surprised noone noticed, but the man who wrote the article passed away several days before the article was published:
http://en.wikipedia.org/wiki/Jef_Raskin
a dead guy is writing articles about code
;)
development from the grave...
come on at least give us a clue about the next
life, is it hot or mild tempered ?
Arash
Arash Partow's Philosophy: Be a person who knows what they don't know, and not a person who doesn't know.
How about collapsing/expanding comment feature that most modern editors have? If you collapse all your comments, you can see code fine, but the comments are still here for those who need them.
May Peace Prevail On Earth
Good code is code that's modularized into so many properly-named, small functions, that it looks like the pseudocode originally used to describe the algorithm in the first place.
Still, if you're implementing some arcane algorithm that isn't documented very well in academia, let alone taught in most universities, and is full of obscure mathematica that even mathematics doctorates will have to squint at, then be a dear and just comment the fucking code to help make it easier for your colleagues to comprehend. If you can implement something so fancy and grandiose that it can have its own patent, certainly you can spend 5 minutes to clarify the principles behind it in documentation as well as sources. It isn't hard.
Slashdot requires you to wait longer between hitting 'reply' and submitting a comment.
I want to laugh when I read it.
Some of it is funny.
Some of it is just scary.
The human mind can be a freakishly messed up thing.
http://mindprod.com/unmaindocumentation.html
It is part of a larger essay about writting crappy code.
Anybody that even comes close to software development
should check it out.
--- begin excerpts ---
Avoid Documenting the "Obvious" :
writing an airline reservation system, make sure there are at
least 25 places in the code that need to be modified if you were
to add another airline. Never document where they are. People who
come after you have no business modifying your code without
thoroughly understanding every line of it.
Units of Measure :
variable, input, output or parameter. e.g. feet, metres, cartons.
This is not so important in bean counting, but it is very important
in engineering work.
As a corollary, never document the units of measure of any conversion
constants, or how the values were derived.
It is mild cheating, but very effective, to salt the code with some
incorrect units of measure in the comments.
If you are feeling particularly malicious, make up your own unit of
measure; name it after yourself or some obscure person and never
define it. If somebody challenges you, tell them you did so that
you could use integer rather than floating point arithmetic.
On the Proper Use of Design Documents :
complicated algorithm, use the classic software engineering principles
of doing a sound design before beginning coding. Write an extremely
detailed design document that describes each step in a very complicated
algorithm. The more detailed this document is, the better.
In fact, the design doc should break the algorithm down into a hierarchy
of structured steps, described in a hierarchy of auto-numbered individual
paragraphs in the document. Use headings at least 5 deep. Make sure that
when you are done, you have broken the structure down so completely that
there are over 500 such auto-numbered paragraphs.
For example, one paragraph might be: (this is a real example)then... (and this is the kicker) when you write the code, for each of these paragraphs
you write a corresponding global function named:Do not document these functions. After all, that's what the
design document is for!
Since the design doc is auto-numbered, it will be extremely difficult
to keep it up to date with changes in the code (because the function
names, of course, are static, not auto-numbered.) This isn't a problem
for you because you will not try to keep the document up to date.
In fact, do everything you can to destroy all traces of the document.
Those who come after you should only be able to find one or two
contradictory, early drafts of the design document hidden on some
dusty shelving in the back room near the dead 286 computers.
--- end excerpts ---
If all I wanted was to grok the way it's executed, I'd just run the program.
If I want to understand why it's executing the way it does, give me comments. Maybe your time is cheap enough that you don't mind looking through 28 dependancy files to finally figure out what pointer is screwing with the function you're trying to debug. Mine isn't.
That Jesus Christ guy is getting some terrible lag... it took him 3 days to respawn! -NJ CoolBreeze
I've heard people say (and have experienced myself) that too many in-code comments tend to clutter a function and make it difficult to read.
As a solution to the problem that exists because I just said it does, I think people far underuse syntax hilighting. I use a darkish blue-green background with white code and black comments. The comments are easily legible, but it is very easy to tune them out to see which lines of code actually "do stuff." With the default black code and green or red comments on a white background in many editors, this benefit is often missed.
-- I prefer the term "karma escort."
In addition, there is a VB for KDE, but there is something very strange about professor unix wanting VB.
I prefer the "u" in honour as it seems to be missing these days.
Use a proper editor, like Emacs or Vim. Setup the autoindentation mode, and use it. In Vim select the whole file, ggVG, and just shoot the autoindent, =. That's it.
After a while on any project, the buzzwords tend to blur together. This is especially true when I begin to work on someone else's part of a project that I'm previously unfamiliar with. Some of the best comments, in my opinion, are those that are written by people who are good writers, not just good coders.
Write comments so that a relative idiot (someone who knows how to code, but doesn't know beans about, say, four different graphics APIs) would understand. Heck, after six months away from my own code, I sometimes feel like an idiot wondering why I put something in a certain place.
As coders, we tend to love long words and big fancy phrases that explain what something does. If, however, we can bite the bullet and divorce ourselves from "Assigns primary responsibility for the node list's functor to the parent's third data field before disconnecting it from the graphics pipeline" in favor of "Stops drawing," we can take a big step towards legibility.
Heck, comments could even *gasp* tell WHY instead of WHAT. Looking at the code it's commenting will tell us WHAT. WHY is often much more cryptic, and a few choice words can clarify it for all readers involved.
-- I prefer the term "karma escort."
Obviously, you have never been to India. India has smart people the same as the USA. But you are attempting to judge India by people that you see in America/UK/Whereever. Well that does not work. Plain and simple, the vast majority of Indian engineers in India are similar to what you will find in BFE America. That is they will have a 2 year degree in CS (actually CIS), or they will have the equivelence of a MS certificate (which is also the same). Then they will get a job with whatever comany they can. Once they have the job, it is their for the rest of their life (or until the jobs start moving to CIS or China).
When you speak about the Indians that are in America, I have been impressed. But they are not your average Indian. In fact, think about the average American who travels over the world. They can assimulate into a culture, are flexible, and typically are soemwhat intelligent; the same as the average Indian here.
Outsourcing is not the problem. The problem is that we got compfortable, and do not work hard enough. When I went to school for CS, I was #1 in all my classes. But right behind me were the Indians and Chinese; Rarely would I find other Americans competing.
I prefer the "u" in honour as it seems to be missing these days.
I believe that only poor programmers comment their code poorly (useless comments, out-of-date comments, etc).
Because of this belief I make an effort to write comments which will assist understanding of any code. (Not saying I am a great programmer, but I care enough to try to be).
Happy moony
they have lots of comments in their code...many of which can't be said on tv
After 40 years of looking at code I have no doubt that code comments are a waste of time and effort. I have spent countless hours reading useless and wrong comments. For me a good software implementation has a data dictionary, informative module/function/class/method headers, and clean self documenting code that has been code reviewed. I can step through most code in my head to figure out what is going on. And, for the code I can't get my head around, there is aways the debugger.
Learning, improving yourself, changing coding style, using new techniques, this all has such a strong impact, that I wouldn't touch my own code from 2005 with a 2-yard pole tied on the end of another 2-yard pole. I'd rewrite it from scratch, making it twice as fast, thrice as reliable and four times more readable. And taking 1/10 the time fixing the old code would take.
Reading your own old code leads only to frustration. ("My god, I'm such a moron to have written this!"). A ton of GOTO in a C program? Excuse me, I'd better take the data files and don't make me look at that. Triple-nested switch()? Hurts! My brain hurts! Condition look-up table organised as some 100x100 array of if() RUN! RUN! IT'S GONNA BLOW!!!!
Anagram("United States of America") == "Dine out, taste a Mac, fries"
There's a fantastic essay describing how to write unmaintainable code. Here's the chapter about comments/documentation: http://mindprod.com/unmaindocumentation.html
For the most part, I find comments useless. They get in the way of quick typing (I hate hitting end and finding the curson beyond a comment, instead of still in the code where I can do something useful,) and they are only necessary if you can't understand the code.
Of course the obvious thought alot of people have is, "What do you do in six months when you come back to make a change?" To this I say that you should eitherremember still (this may be difficult if you spent most of your time commenting rather than coding,) or you should figure it out pretty quickly as you glance through the code (if you can't, then how did you manage to write it in the first place?)
Don't get me wrong. I think that comments CAN be useful. I just think that people tend to rely on them too much. I use comments as placeholders for sections of code I'll write later, and for tricky stuff sometimes, such as extensive bit manipulations, but I don't think there's much reason to use them elsewhere. Proper name choices will tell you enough to get going quickly, and if you're trying to alter things on a more detailed level, you'd better understand the code anyway.
There's also an additional problem with comments in certain languages. In Scheme, for instance, when you can easily end up with very small, but powerful functions that have mutual recursion with multiple other functions, comments wouldn't really make sense. You would need to understand the functions already just to follow the order of execution in order to tell which comments you should even be looking at.
I am surprised nobody has brought up literate programming yet. Completely flips over the relationship between code and comments. You are principally writing a document for human consumption. One in a while, you also toss in a little fragment of code for the computer's benefit.
I'll take unit tests over comments any day. Unit tests are an executable explanation of what the code should do. Comments get out of date and ignored. A well written unit test says exactly what sort of service the method is providing and what the implications of that method call are assumed to be. The important thing to notice here is that it doesn't tell HOW the code is doing it. This, of course is GREAT! If the code is hard to read, get unit test coverage, understand it, "comment" it with tests, and refactor the hell out of it.
*** Sigs are a stupid waste of bandwidth.
I know it sounds stupid, but having to go through the code helps me to understand it much better than just reading comments. You see, the problem is that as much as a developer might comment his/her code, he/she will give as obvious some things that might be not so obvious, thus, you end up supposing you understand the code when you really do not. On the other hand, having to look at it deeply in order to understand it, gives you a better understanding. I like to use the GPS analogy with this: When you use the GPS you can move around a city quick, but once you disable the GPS, you have the impression that you've never been to the city. Never use the GPS, and in one week you'll know the city by heart.
*Why* the function does what it does. Cite a paper, report, equation number or page.
Oooh, someone hasn't watched Pulp Fiction.
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.
Your colleagues are almost completely wrong. "Short, descriptive variable names" will do when the algorithm is trivial and its function obvious.
This afternoon, however, I wrote a chunk of code that takes a long series of colored line segments (identified by clr, x1, y1, x2, y2) and figures out how many closed polygons they describe. My variable names are all short and descriptive, but without at least a little introductory comment, most programmers probably wouldn't know what was going on without a whole lot of head-scratching. It's not that the code is that terribly complex, but all software ever does is move numbers around, and unless you know what the numbers are supposed to represent, it's just gibberish.
Proud member of the Weirdo-American community.
The code should be written so that it is obviously WHAT it does.
:-) Like when I go "ok, it's doing that... But WHY?", I know that I should have put in a comment. But if I go "WHAT the f**k is it doing here", those lines should be rewritten.
The comment should explain WHY.
Not that I use that convention myself, but I often wish that I did
"Always code as if the person who ends up maintaining your code
will be a violent psychopath who knows where you live.
John F. Woods (quoted on Usenet) 1997/08/20"
Put "document" between "Always" and "code" and the psychopath probably will be less violent...
Recent events have caused me to conclude that source code has no value to a software company.
The value is in the understanding on the part of the engineers who develop the software, who then develop the software to their understanding, which software gets sold.
Without this understanding, the engineers and coders produce crap and the company goes belly-up. Given the understanding, they produce wonders that are well received and highly appreciated by customers who happily pay on time.
So, the thing of most apparent value, and that which is sold, (the software) in truth is the LEAST significant assett for the software company.
It's the understanding of the industry for which the software is to be written. It's knowing all the approaches that didn't work. It's knowing the terminology of the target industry. It's knowing what's already been tried, and why it did (or did not) work.
The source code is merely a condensed, lossy format for preserving this knowledge.
It's difficult to grasp - and yet critical for the long-term survival of a software company!
I have no problem with your religion until you decide it's reason to deprive others of the truth.
Properly commented/documented code is one of those things that is hard to describe, but you know it when you see it (or don't see it).
;)).
If I'm working on a routine complicated enough that it forces me to think about the problem in pseudo code before actually writing the code, the pseudo code ends up being left behind as comments in the code. This allows me to focus on mini-parts of the problem without losing focus, and also tends to appropriately describe what is going on at a high level (assuming of course your code does what you think it does
If I'm trying to figure out what a piece of code does, and it takes awhile to dawn on me, I add a comment.
If I fix a wierd bug that doesn't look like a bug, in goes a comment to describe the buggy behavior so that someone else doesn't come in and make the same mistake a 2nd time. Sometimes I'll just comment out a line and add text above it which says "don't do this because of blah".
If I do something non-obvious/clever/evil, in goes a comment.
If time allows, I create "headers" for functions that describe what the function does, what the parameters are for, what all of the expected return values in various cases are, and what exceptions the code may throw (if any). I tend to do this more for core pieces of code than code that is rarely touched or considered throw-away.
It's not just that the programs to write are small, it's that they're write-only. You write them once, get graded, that's it. We churn generation after generation of students who are taught that code is written once, then never ever maintained.
Sure, you learn lots of things about design, software engineering, etc, in university, but they're pure theory. And seemingly useless theory at the moment. There is _nothing_ to illustrate there why some code organization is good, and why spagetti code is bad. All those lessons about maintenance as wasted when you never have to maintain anything, nor ever write anything big enough.
So while I'll say your idea does have merit, I think it can be done better. Don't just give them 1000 lines of someone else's code. Make them keep building and expanding the same program until the last year.
E.g., ok, in introductory programming they had to write some 100 line trivial program. But don't throw it away. When the next course comes along, give them the assignment to change or expand that original program.
E.g., if at some point you also get a computer graphics course, make them add a graphics module to that program. GUI programming? Sure, add a GUI to it. Database programming? Sure, make it save the data in a database. YACC? Ok, make them add a small scripting language to it. Different language? Make them port it to that language. Etc.
Make it a part of the grade to explain _what_ had to be changed and _why_.
Eventually it _will_ grow to be 1000 lines, and then it will grow even larger. And more importantly it'll be example of why code has to be readable and maintainable.
A polar bear is a cartesian bear after a coordinate transform.
Hmmm, most modern programmers would just pick "Tools->Beautify Code" in their modern editor and not care how the other person formatted their code.
But surely, "beauty is in the eye of the beholder" and not someone else's formating algorithm?
I don't understand why people don't use more descriptive variable names. For something stupidly simple like a counter in a 'for' loop, the iterating variable could easily be 'ctr' instead of 'c'. There is zero performance hit and everyone understands the code more clearly. TWO LETTERS, come on man!
Going further... in c++ member functions and variables should be more descriptive. For instance, in a variable length array class, (mMaxArrayLength, mCurrentArrayLength) are much much better than (max, len) which is the common lexicon.
I feel (at least in c++) that documentation should only be used to explain high level functionality, the inner workings of a fucntion/method should be evident by the variable/method/class names. It doesn't add code size or decrease performance in any way. And, with the advent of copy and paste, it doesn't really slow development time either.
BUT.... Even more important than that is consistancy. Whatever coding/documenting style is chosen for a particular project, for god sakes, stick with it. Nine out of ten coding/documenting styles will be exactly the same, with little changes here and there. The most important thing is be consistant with the whole project.
end of rant
Fast Federal Court and I.T.C. updates
I find that the most useful comments clarify the underlying code by adding something that may not be possible to get from the code itself. For example the intention of the code may or may not be clear (the code may be incorrect or it could 'mean' several things given the context) but a comment can be explicit about the intention.
The point is you are not repeating the code statements- you are adding information to the source code. This makes it a lot less likely the comment is going to go out of date. In many cases you can change code and the comment will still remain the same (you are still searching a hash for the RequestItemId- just doing it faster/better/correctly).
Programming is about translating concepts from a problem domain (Billing, Accounting, CRM, Networking, Memory Paging) into code (be it C, C++, Java, Perl, Pascal..). We endeavour to build functions, methods and objects that map to the problem domain (so we can display a picture, act on a button click, add a charge to a customer's bill...). But this translation inevitably has some tricky bits that are not clear from the code (what format is the time in? why do we have to mask of the data retrieved from disk? why aren't we validating the customer's username?). So it can be useful to put the 'original' (our intention) in there and any useful translation notes (the tricky or non-obvious bits) so that we can make it clear where something is done or not done deliberately- and when it is simply an error.
Good comments add information not necessarily obvious from code. That makes it tricky to write good comments since you have to look at the code as if you had never seen it before and ask: what isn't obvious about this? Which is why writing the comments before you write the code can be much more effective. After you've written the code it just feels like you are stating the obvious. Which it is- to you, at that moment in time.
Aside from taking people with >5 years industrial programmamming experience, and then forcing them to do a basic Java course using BlueJ, the standard of the markers is questionable.
Imagine my surprise when I recieved my final assignment back with the comment "No Comments!" (which there were). Perhaps the ultimate irony was that "No Comments!" was actually written over a comment.... muppets....
The discussion seems to focus on in-source comments, and polarises on whether to comment there or not.
Your post at least gets away from that, but there are more places where to comment. It depends on the type of comment.
Places where to comment:
- there's the headers
- when checking in a revision in the repository , document per file. So that if you do a diff between revisions, you get the background behind the change. That background belongs to that moment in time. This mechanism is probably underused.
- and document the whole checkin. Lavishly.
- and add to that a place for the general thinking and design around the subject.
There should be lots of effort for documentation, but each time the question is, where does it go.
I still think that if you show me comments in the source , I'll show you an opportunity to improve the source.
Obviously, if the ideas behind extreme programming lead to a situation where bad code is badly documented, then instead of one problem, you got two.
Those who understand binary, and those who dont.
:(
Sorry!
Good comments are not there to document what is obvious from reading the code they must add another information that one will not easily get otherwise.
For example, instead of a comment that explains *how* something works write comments when it's necessary to explain *why* you implemented things that way.
True warriors use the Klingon Google
Assembly is what taught me to use lots of comments. Every single line did have a comment, flowing like a column of text alongside the code, documenting what, why and how I've done.
I also very quickly learned to not use the "Decrement register ax and jump if not zero" kind of comments, but rather stuff like "if we got this far, the data must be valid, so store it and move to the next record".
Assembly is very cryptic stuff, as you already know. A 100 line C function can become a 1000 line ASM module. Worse yet, some 10 lines of C which are easily read, easily held in your head, and easily visible at the same time on the screen, can easily become 50 to 100 lines of assembly, which aren't either. You document it well, or you can't read it later.
So personally I'd say teach the students assembly early, and make them maintain that code the next semester. That should drive the point home about comments and software engineering.
A polar bear is a cartesian bear after a coordinate transform.
I think that the only comment that you really need are: //FIXME reason //HACK what is the hack and why is present here //TODO what there is to-do
at the end of the day I parse all my code and point out what to do and what to fix. Other comment are pretty useless.
Tests cannot be generic. It is impossible to test all possible code paths, there are infinitely many.Your tests are only going to cover a couple of use cases. So tests do not fully document functionality.
M-<
C-Space
M->
C-M-\
Tabs normalized.
The article author says "I discard the radical position taken by proponents of extreme programming (XP) to get rid of 'unnecessary' documentation."
Why? Surely no one wants to write 'unnecessary' documentation and comments? That would be a waste of time wouldn't it?
As everyone agrees that you should put in 'necessary' documentation/comments then what's the problem? Rather than setting up a false dicotomy between commenting and not-commenting wouldn't it be better to try and work out what the necessary documentation is?
Comments are good, no question. But they must be made on the right level of detail. Commenting every single line is complete overkill and helps only those who are completely unfamiliar with the language. So this may be useful for educational purposes, but not for real world code.
//read input //process bla bla //find data
When I inherit an existing code base, first thing I do is try to get the overall structure. In Java this is pretty obvious when the packages are well organized and have good names. Next I look into individual packages. There should be a package.html that quickly describes what this package does, what it should not do, and so on. This is still no comments in the classical sense.
Next I look at class names. My IDE also distinguishes interfaces from classes, so they are easily spotted. No need to use naming conventions for interfaces and the like, though. Good class names already tell you a lot how things probably work and it's easy to figure out.
The details of the classes responsibilities are in the class documentation at the top. This one I consider an essential comment. Knowing how to use this class, if it's thread-safe, immutable, it's contract etc. is the most important thing.
Next the contract of the individual methods is important. So at least all the public and protected methods must have a good comment describing the contract in detail. Note: I am not interested in HOW a method performs a job, but only what goes in and in what state does it leave the object.
Finally to comments on individual code blocks and private methods: use comments only when an algorithm is not obvious, when an arithmetic expressions needs explanation, when the reason for a thing you do is not obvious. Also document constructs that are very delicate when changed and likely to break something.
Often I see code like this:
[some lines of code]
[some more lines of code]
[some more lines of code]
Instead of placing comments in front of each code block the code should have been broken up into smaller methods that have a speaking name.
Why do you say "genius programmer", and not "genius, and inscrutible programmer"?
Did nobody tell Mr "Genius" that his code was unreadable, that this was stupid, and that he could do better if he was actually as smart as he thought, and was any good at programming?
My Karma: ran over your Dogma
StrawberryFrog
In highschool, we got taught to add lots of comments, even when my rebelious uprisings didn't change this. I refused to comment silly lines like a = 25; And on my first exam I did get degraded because of this. So then I just started adding larger blocks of comments to blocks of code. When on work experience, I got told by someone in the company that it's best not to comment your code, because once the project is finished, and they let you go.. then need to upgrade their code, I (as the programmer) would be pretty much the only one that could read my code. Meaning I'd always (mostly) have a job, because other programmers would waste their time trying to decode what I wrote. On one side, this is a nice idea... on the otherside, it's pretty rediculous, seeing as that after a few months I probably won't even remember what I coded in the first place. So now I just tend to add comments on a regular basis, but not on every line. In college they don't even teach us to use comments... which is odd.. although in this so called CS course we're only using VB.NET... quite sickening.
Wow, it still amazes me how far behind Software Engineering is when compared to the rest of the modern world. I can't think of any other engineering nor scientific disciplin which could get away with stuff like this. You might think that I am a bit harsh, and you are probably right, but let me explain why through an example.
/../ some more anecdotal 'evidence'."
...after completing the survey we chose to interview X number of people in order to find out how each respondant observed the situation where they were to interpret different types of code comments /../ We also discussed the issue with a psychologist and a didactics specialist and we found striking similarities between comment writing and writing tutoring books and..."
The programmer/homebrew way to solve (or rather, explain away) the Lack of Comment (LoC) problem: "I have worked as an X for Y years and I have found that this and only this works. People shouldn't be so lazy, people are stupid, management is stupid, customers are usually right, the programming languages needs more technical features bla bla bla
No, this simply isn't good enough. We have to do better than that. Let's instead try what engineers do best: engineering.
The engineering/positivism way to try to solve LoC: "We first have to realize that there are two different approaches to this problem; the comment writer perpective and the comment reader perspective. We then subdivide each area into a number of distinct sub-cases which..."
While this might seem like a good way to solve a problem such as LoC, we have to realize that we are trying to systematize people. And, as our short and turtle slow SE history will show us, it will simply not work. We are all human beings and cannot be dealt with in this way with any degree of success. What else can we try? Let's go for some other type of science:
The social science/hermenutic way to try to solve LoC:
Is this the ultimate way to solve problems like this? In all likelyhood no. But I am willing to bet that this is as good as we're going to get at this point in time. And while reading anecdotes can be entertaining, it is still only one persons highly subjective opinion and there is NO WAY that we will advance another centimeter (or inch, for the world standard challenged) if we don't fix this way of thinking about software development issues. Right now.
you should not have anything to do in the business of programming. I almost never put any comment in my code, it is way more readable and maintenable than my neighbour's code, where you have to look for code inside the comment jungle.
Open it in Wordpad and it will indent properly
The comments from the TAs about near useless comments was interesting.
Getting people to do any comments is a conversation in itself.
However, the TAs brought up a good point. It is not enough to put ANY comments in a file, you need to put GOOD comments in, but who teaches people what good commenting is?
What works for me is
- putting a small paragraph at the top of file
explaining, in general, what the file is for
( sort of like labeling a jar with the preserves
you just put into it )
- putting a 1-2 line description above each
non-trivial function
- putting a sentence fragment above each
significant or non intuitive ( coding around a
quirk ) block of code
I get compliments on how easy it is to understand and maintain my code( often resulting in me getting to asked to write more code - versus the folks who intentionally obscure things in the pursuit of job security ). I can also go back to code I wrote years ago and understand what it is going on.
I put comments in as I write the code, mostly, so it doesn't feel like a burden.
If anyone has any other good idea, please do tell, someone somewhere is likely to give it a try.
If you think it is hard for *you* to determine what your code does two years after you wrote it, think about what you are expecting some poor patent examiner to do when examining a software patent.
How the hell do you expect a patent examiner (or for that matter, an attorney representing some poor clod being sued) to decipher your code and discover that it is prior art that invalidates some claim in a software patent if *you* can't even figure out what *your own* code does a couple of years after you wrote it?
If nothing else, *that's* a good reason to write coherent, *understandable* comments for your code that do more than parrot the C-language (or whatever) statements on each line of code.
The methods: "using short, descriptive variable names", "write code based on good documentation" and "write plenty clarifying comments in the code" simply don't contradict.
You should use all of them.
Sindri Traustason.
One of my friends has a policy that the first thing he does when attempting to maintain some (usually badly written) program passed onto him is to strip out the comments so that he will not be misled.
I don't take such extreme measures myself - descriptions of procedure parameters and return values and references to unusual or clever algorithms are a good idea. Warnings like You are not expected to understand this or You are advised in your own best interests not to modify the following code without contacting ...* also have their uses.
* Most slashdotters will know the origin of the first of these quotations, but how many know where the second one comes from? (unless you have looked at an assembly language known as GIN5 you are unlikely to be even able to guess!).
What you are saying is BLINDINGLY obvious !
In addition, there is no such thing as "self-documenting" code - the concept is utter rubbish.
If you write code and don't comment it then you basically get what you deserve when you then try and maintain it years later.
Code that is not sufficiently commented is at worse (ie - usually) unmaintainable, and at best very expensive to maintain.
Simple.
this problem is not solvable. a pretty cool site is www.thedailywtf.com. It shows real-life, real-world, real-pain programming horrors that happen each and every day. The worst ones are the ones that are best commented.
written in WordPerfect (the format was available, if not quite open).
We wrote the documentation first and it was great. That was when I learned to hate Smalltalk's layout, so I changed its pretty printer to make some sense and used that instead to indent the output.
MSBPodcast.com The opinions expressed here are my own. If you don't like 'em... Think up your own stuff.
I teach computer programming part time at a local college - when students sign-up :(. 50% of their grade is based on their comments. I have spent too many years in industry to dismiss that value of good comments in code. Commenting first helps you think through your solution then you stomp down your code and clean-up your comments. Time and again this will take you LESS time and produce higher quality code then just banging away.
Bull, Checked Exceptions are More Important the comments.
Had the unhappy experience of having to write a library for Dot Net. With No Checked Exceptions it was IMPOSSIBLE to pass along to the user of the class information about what Exceptions the class metheds threw.
I could document the exceptions, which no one will read
I could put doc in the class as comments which no one will read...
I decided to make each method WRITE it's list of EXCEPTIONS TO Console.out.
That solves the problem for anyone calling the library from within VisualStudio, But what about ASP.
The real problem is LAZY Companies attempting to copy JAVA and get it WRONG.
You know what, I have seen lots of Assembly language code for airlines, and i think the programs are *more often than not* well commented. A lengthy program header explains the programs relevance in the application, when it will be called, who will call it, in what process, its input/output etc etc. All subroutines also have a subroutine header which describes what it does, the input it expects/receives and the output - normal as well as in error scenario. This documentation - being assembly language - is down to the last bit! literally...Then the instructions are also well commented , most of the time i can get around with only reading the comments.
There is quite a few reasons these languages are not more commonly used. Lets take Z for example, Z is a specification language you state with a form of set notation what the program should do (not how). However no client can read and understand your specification so determining if it's correct is very difficult. You then do lots of design work about the how, there is no method to automatically move from the what to the how(VDM attempts to address this but it's still far from automatic). You then implement, and test your code. Then find out the spec is not exactly what the client wanted fix test and so on. This is a very long winded process slow process which in the end does not guarantee any thing. Rapid prototyping in practice works a lot better you talk to your client get an idea of the data they wish to store and how they what to use it. Knock up some sample throw away screens to confirm with you client that you have understood what they meant, this stage gets repeated a few times. With reference to that, design data structures, and code tree, then implement and test. While all the time though you have the reference screens, and the ability to keep popping back to the client. This method is faster, the client gets constant feed back of how their app is taking shape. The problem with formal methods is a limited number of people can understand them and they don't work that well in real situations. They consume a lot of time for very little piratical gain. Ask IBM how much software they developed using VDM and they invented it. A lot of these formal methods are created by people who either can't program or have not done so for such along time they have no concept of how the industry works. They write their methods as an idealized version of how things should work and ignoring a lot of the human factor. There is always an in-built assumption that clients know what they want a system to do, or that the requirements can magically be divined by the people involved in the project.
Some of those are on my top ten don't list.
Why do you need to repeat the name of the function? It's right there in the code. IME, this is one of the most common times when comments get out of sync with reality. Duplicating function names, parameter names, etc. adds no value, and can be misleading.
Code with personal annotations should never be released. 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. In any case, the whole project dev team doesn't need to know that someone, somewhere didn't understand something.
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. If I can, then whoever wrote it probably didn't fit it into the surrounding code and/or follow coding standards properly.
Obviously, comments that cite a particular bug reference can be useful. Also, you can always look up who changed something and when using source control if you really need to ask them something, and that will get you information guaranteed to be accurate without the need for potentially misleading comments.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
http://www.cenqua.com/commentator/
Sneak teach kids Algebra using a game
They are wrong, you are right.
"Education is not the filling of a pail, but the lighting of a fire." -- William Butler Yeats
When I was learning C in college in the late 80s, a professor insisted that the programs we turned in for our assignments have an *average* of one line of comments per line of code.
I thought he was a nut.
Later, when I got into programming for a living during the early 90s (since left for greener pastures), and was writing code that I had to maintain, I decided to check my comment-to-code ratio on code that I was producing. Darn if it wasn't an average of 1:1. Several years later, I was able to dig that code up, and I found I could tell what a module or function was supposed to do and how it worked.
Good commenting, like good end-user documentation, is a lost art these days. Programming courses don't emphasize it enough, and programmers in general would rather whine than write decent comments for the people who'll have to maintain their code. And management-types are the worst offenders, because they have no comprehension of the value, and hence won't budget the time needed to do it right, nor insist that it be done.
Basically, software engineering is dead, and has been replaced by code monkeys who pound out code that management hopes to sell as the latest from Shakespeare.
Comments, at ***BEST***, tell you what the author of the comment *hopes* was going on, at the time it was written. The code that follows may well not do anything of the sort; it may have, at one point, only to have been re-written by somebody else at a later date; it may still do what was stated, though that's no longer what's needed.
Code can have bugs and it doesn't always do what was intended. Sometimes comments have errors too.
We don't throw up our hands and say "never write code, it might not be perfect", so why do that over incorrect comments?
Learn to do your job right. Don't depend on what was written in any comments. The compiler ignores comments; so should you.
As your own experience showed you, sometimes what was written in the code can't be depended on either. Compilers can have bugs too.
There's nothing more annoying than old, out-of-date, or just plain confusing commments used as an excuse to explain poorly written code. Ban all comments and work on making your code compact and easy to read and understand. I'd much rather read 20 lines of well written code than 50 lines of garbage with another 20 lines of comments as an excuse for not writing it better in first place.
That reminds me of a humorous anecdote:
One of my computer courses in college was Software Design, where they teach you how to document and plan before you code, and various development models.
One day the teacher was going over all different models, the first of which being "Code and Fix". Right after she said that, half the students cheered. Her response was a sigh and a shrug...but it was clear that everyone knew what reality was, and still is.
One note of interest: This was not an introductory, or even first year programming course. This was my 6th, maybe 7th course even...
Probably the single most useful post in this entire thread!
The whole point of the code/comments it to create a computer program that does some function. This can be accomplished without a single comment, but can't be without code. I appreciate code that has what I call "good comments", but code that has wordy, or even innaccurate comments (which is over half the code I look at) is less readable than the plain code. A lot of times the comment says one thing, while the code does something else.
I think if you are going to be competent enough to write software in a given language, then you should be able to read it fluently - hence no need for a lot of comments in the middle of code. There are a few times were something tricky is being done, or there is some interaction with code in another location, where you need a brief statement to remind a later reviewer of such things, and some documentation in the interfaces (headers) is nice - IF KEPT CURRENT AND UP-TO-DATE WITH THE CODE!
Re: "That comment is a good match for the code it is with. I never write comments like that unless dealing with a 3rd party interface, or something else that is a brick wall I can't refactor across, and there is something very quirky or unusual about it."
I think there's an important point there. Code == documentation makes the assumption that the code is clear. Many times it isn't -possible- to make the code as clear as it needs to be to be useful as documentation. Third-party code is one of the reasons; time constraints and legacy codebases are a couple of others.
I remember once in the newsgroups, P. J. Plaugher was discussing the C++ Standard Library implementation in VC6, and mentioned that one reason the code was unclear was because of compiler limits; when VC expanded certain templates, the identifiers for some template classes exceeded the compiler's limits.
What else makes it more difficult or impossible to write code that is clear enough to be documentation?
"Any time/money you save by cheaping out now, you'll wind up having to pay back twice over on the back end."
True enough. I subscribe to the philosophy of doing things the best right way personally, too.
But any manager could tell you that there is a time value to money, getting that money in hand sooner rather than later is better, and with the interest made on that money we can patch things up only as much as absolutely necessary (kind of like how successful landlords work - they want the money right now and they'll get to kludgy repairs some time next week as soon as he can get hold of that guy that does slipshod work for cheap).
"Provided by the management for your protection."
The "really best algorithm" is always self evident and writting and maintaining "commnets for dummies" is a waste of time.
Moreover, I write open source. Why should I make it easy for you to rip off and steal it? If you can't figure it out, patches are welcome.
What about your version control system? You are using version control, aren't you?
That is how I view every possible interaction I ever have.
...
If it was hard to code, it should be hard to read.
The subject says it all, no more comment needed :)
Well what do you expect, when evil professors tell students that they must comment EVERY line of code or lose points on their grade? That was my experience.
That's why there's so much aversion to documentation. Many, if not most, people are averse to writing in any language. Their spelling isn't great, or their grammar isn't quite right, or they have some trauma they experienced in English class. These people develop an aversion to writing.
I like to write, to the point where I can even tolerate editing second and third drafts. Not surprisingly, I like to document code, edit the documentation, and even re-document code correctly if I screw it up the first time.
I do not, however, like the literate programming style. That's a whole different thing. My favorite style of documentation is JavaDoc, or PHPDocumentor.
JavaDoc rewards you for writing extensive documentation for your interfaces, and penalizes you for writing lots of comments in your code. It encourages you to develop a narrative about your objects, rather than a detailed outline of your code.
Not that there's something wrong with outlining code! I often start coding by writing a couple dozen lines of documentation about the specific alorithms and methods I'm using to implement a function. This kind of "documentation", however, isn't that useful to someone who needs to figure out if they're making changes in the right part of the application.
They need the overview, and that takes more effort to write.
PS - I'm not a big believer in using accurate variable names everywhere. I think it's often better to use generic names, preferably the ones used in the examples in the man pages, and explain what's going on in a couple lines above the code. Once you have the output you want, save the values to variables with long names, or better, save them into objects. Here's what I mean:
result = query("some query:);
for (i=0; i=next(result); out += i);
total_hours = out;
result = query("some other query:);
for (i=0; i=next(result); out += i);
total_break_time = out;
It's better to reuse the variables, because it's a way to signal to the reader that in both blocks of code, we're doing the exact same thing. This is "idiomatic" programming. At the top of the block, you "set up" the unique aspects of the block. At the bottom of the block of code, the output is assigned to a unique variable.
Arguably, you can put the repetitive code into a function or macro. However, it's not always worth the extra effort, and can be confusing if you have two or three very short, very similar function that differ in just one or two lines. Sometimes, unfactored code is okay.
I used to be a technical writer. I really come at code form a documenter's point of view. I found that comments do more to CLEAN UP my code than anything else. Commenting really forces me to consider what I am looking at and what's I'm doing. Comments are great. Good code will never be self-documenting. There's more to good code than variable names. I use comments to describe intent. I use comments to point out idiosynchrasies, and why those are in the code. I use comments to explain the overall logic of the code, and the logic at specific points. All that helps me to find and fix problems faster. That helps me to know where in the code to add new code. That helps me to compare my intent with my execution. And more importantly, this helps the next person greatly.
from arch/sparc/lib/sdiv.S in the linux kernel. /* (I do not understand this) */ :D
! %o5 > %o3: went too far: back up 1 step
! srl %o5, 1, %o5
! dec %g7
! do single-bit divide steps
Help me get a PSP! Who can afford s
Our's banned comments because he said it made the executable bigger. Not a problem since the project never shipped. =)
"I hate to advocate drugs, alcohol, violence or insanity but they've always worked for me" - HST
All taxing the wealthy does is drive economic activity out of the US.
Tell that to Bill Clinton.
Code is more important than comments. It's what you're actually writing purposefully - so write it clearly in the language which other programmers understand. If we both know C++, why must we drench your program in English translations of what has already been written in a language we both know?
Obfuscated or clever coding, obscure enough to require comments, is rarely needed. If someone needs a comment to understand what you've coded, you probably can de-obfuscate the code better and make it more readable (and thus probably less buggy). On the whole, code should explain itself as the ultimate detailed documentation of what the computer must do; context, decomposition, and meaningful naming does far more in most cases to explain what is happening than translating that linguistic expression into another language.
Write code for other programmers. They know the language - write in a manner which they can understand in that language. Doing so largely eliminates the need to subsequently translate that into another language.
Yes, comments are occasionally necessary. Some things just make more sense when expressed in another language. Most of the time, just write clearly in whatever language is most appropriate; for programmers, get literate in C++, Java, SmallTalk, whatever.
Can we get a "-1 Wrong" moderation option?
So the piece's co-worker/opponent thinks all you need is short, descriptive variable names. Conditions? Functions?
Oh, and when were those short, self-descriptive names chosen - 0337, 18 hours after your first coffee of the day?
mark "i_blertfk"
if (codeIsWellWritten)
{
writeCodeWithoutComments()
}
else
{
writeCommentsThatWillSoonBeOutOfDate()
}
I thought this was a pretty interesting topic seeing as I was up until the wee hours of the morning last night doing some major programming for one of my final assignments.
This was a group assignment so we have essentially 3 guys, 2 who are programmers working on the same project. I do a bulk of the programming so most of the code there is mine, but the other programmer has a style of coding completely opposite of mine.
We're coding this thing in J# which we all taught ourselves. We're all hug java fans so that's why we chose this language.
Our code has basically no commenting. It did at first in the early stages of development, but as things took off, the code doubled and tripled and soon there was so much. I think the main reason for this is because many of the forms used follow the same logic, all have similar functions (but not similar enough to design a class to handle all the operations). Anyway, since I was project lead, and I did most of the bulk code, I knew what was going on at any point in time - since it was my logic. The other programmers code which handled different operations was not so readable - but he probably thinks the same as mine since I specialized in the part of the application which handled interacting with the database.
The following are things that I think greatly aid the readability of code between programmers:
1) Good Variable Names - descriptive, but not a novel, short, but not an abbreviation of an abbreviation you've made yourself.
2) Follow flow and use proper indenting. Methods, functions, subroutines, all that should be indented properly. So many times I rely on the indenting to understand the flow of the application.
3) Comment difficult procedures. If something has caused you a lot of grief to program, document what the hell it is that you came up with. A programmer trying to interpret your code is going to be just as confused as you were when you encountered the problem. If you document how you solved that problem, or why you chose to do what you did your teammates are going to love you.
I guess there can be excessive commenting and what's required. With good variable names, proper indentation, and comments guiding the readers of your code through the more difficult areas you'll be fine. I mean hell, if they don't know a thing aabout programming to begin with, why would they be reading? You should assume the reader has at least a minimal understanding of programming logic.
Yes, I am a programmer.
Forget about other people. Worry about yourself. If you document code so that you would be able to come back after 5-10 years and be able to pick up where you left off with just a little bit of time reading comments, it'll be good enough for anyone.
// Holy frijoles! Our pointer ended up NULL, and now we're boned. Call the failover case and clean up.
For you 'genius' programmers out there that don't need comments: you're lying. I find most people that take that stance end up just hacking up a solution to their problem and cramming it in, regardless of thee appropriateness, and spend a lot of time complaining and debugging (though still never really getting everything working quite as well as would be liked).
Besides, commenting code is fun. It gives you an extra chance to be creative during the day. You can be conversational in your comments. I don't see anything wrong with comments that read like:
Sometimes, if you're under stress, you may want to reduce that timeframe. In University, I spent a whole weekend awake and working on a project. At some point, I was adding documentation so I could remember what I was doing 4 LINES ago. Ideally, don't code tired, I guess. Barring that, though, make the comments work for you.
if (!(strFilter == R996 && NoChanges(pStruct))) { ...
}
Anyone who took CS141 can tell you this is one of the first things taught. One of my teachers went so far that 25% of your grade (for that programming project) was based on your comments and your flow chart.
I mod down so you can mod up. Your welcome.
Just because you understand your code today does not mean you'll remember why you did it that way six years, or even six months, from now. It's happened to you. It's happened to me, too, and to lots of others.
Notice that in the tech books filled with big slabs of code, code crafted *specifically* to teach the reader, the author still has to explain, sometimes at considerable length, what the code does and why it does it that way.
Poor commentary is a waste of time -- it only tells you what the code tells you. This is true. But good commentary tells you things that cannot be expressed in the code. Things you'll need to know if you want to repair or recast or reuse the code.
But aside from that, writing good, durable commentary helps you to build better code in the first place, by making you think twice, in two different ways, about what you are doing. I wish I could recall specific examples, but I'm sure that more than once I've saved myself from error when I looked at the comments I wrote and said, "that's nonsense -- what is really going on here?"
You should have an external document that says what and how your system should do. Constraint and validation definitions should be there. When users propose a change, update that document and review the proposed changes with them. Then implement the agreed on changes in the code. Comments should be limited. Code should be kept in a source control program with versioning and old commented out code should be removed after a few months to a year if not immediately. In my experience comments are often wrong on code which has been maintained more than a few years by more than a few programs. You should require all variable names to be descriptive if their scope is more than a tight loop. Code should be reviewed by another programmer before it is installed. You should use a program that does automatic validation of your minimal coding standards.
She was like chocolate when she drank... semi-sweet at first and then increasingly bitter.
Have these people come up with a big bunch of code that is self documenting. Then if they can, which they won't, how much of that code exists, even if people are trying? Less than 5% certainly.
One great OO evil I see is instead of allowing "a=b", which would be obvious, you must do SetValueOfA(GetValueOfB()); Which simply retrieves the private copy of B and sets the private copy of a. If "A" is doing something critical, e.g. in an embedded system, so it must be limited as to range, how fast it changes, or validated against other variables to keep things safe or sane, use SetValueOfA, as it tells you that it is doing something more than a=arg in the body.
Comments are similar. First, the worst peeve is when they get out of sync. More comments, the more likely they are to get out of sync when code changes but comments (some may be a few lines away, or at the function header, etc.) don't so you are trying to figure out which of two has a bug.
When the function of code is clear from the topology, local variable names should make things clear (I use i,j,k for throwaway indexes, curtated names for temporaries, e.g. something in converted engineering units, and longer names for important variables).
Many comments are very important indicating subtlety, e.g. if you are accessing something from a buffer which is really a struct but don't want to worry about doing unions and endians, it would be made very clear by simply saying "Pulling a 32 bit unsigned as record size starting at byte 8" - and that comment would be clearer than doing the union/struct/htonl stuff.
Comments ought to be like a gloss on the code, explaining the subtleties or exceptions. When something appears simple but is doing something underneath, it needs commenting. Or if you doing something where EOF will be an exception or signal handled completely outside the block of code so it doesn't appear you forgot.
They should be few because if these critical comments are merely a half-dozen among several hundred, how do you find them? Look for "CRITICAL:" - will that be maintained?
Good code with clear topology (see "The Programmer's Stone" on the Quality Plateau), with comments bringing into high relief the nonobvious is a beautiful balance - for lack of a better word, it is Zen.
Comments won't fix badly written code. Good code won't be helped, and may be obfuscated by lots of redundant text (isn't it better to see the whole routine on one screen, than have to scroll across several because every operation occurs twice - once in code and once in comments?).
Unit tests will show how a method is used. This should be enough documentation on the use of a method. In addition, the unit test will tell you when you have broken your code with a bug fix(a regression).
I supplement the above with class diagrams and most importantly sequence diagrams. The value in a class diagram is kind of obvious. But what comments lack, and to a degree unit tests, is showing the overall sequence that occurs. This should diagram the interaction of events. The digram illustrates when certain methods are called, what methods they call and what returns the caller receives. There are a number of other useful diagrams like the collaboration/deployment, state, activity, and last, but not least, Use Case diagrams. Without the code being associated with a Use Case, it can be argued you are writing code that adds no value to the code; in other words, you are just wasting resources.
- Just my $0.02, take with a grain of salt, your mileage may vary.
My new rule of thumb is that if I can fix a bug in Emacs in less time than it takes Eclipse to start, I use Emacs.
I haven't fired up Eclipse in weeks.
For those not in the know - JDE! It does enough that you can live without Eclipse (or anything else for that matter).
Then use NetBeans for debugging because it takes about a second to mount your source tree and start debugging against it. Does it care you don't have libraires defined to build? Nope! It just lets you debug assuming that the reason you pointed it at that source is that it was correct for the debugging session!
"There is more worth loving than we have strength to love." - Brian Jay Stanley
I don't think you have a proper understanding of computer courses. It doesn't matter how clear the variable names are, the checkbox for the professor is "are there comments". Code is not comments, and therefore that code would have got him docked just as badly.
"There is more worth loving than we have strength to love." - Brian Jay Stanley
"Hey, why is the compile taking so long? It's been over an hour!"
"Well, you see, there's a new doclet that inserts a comment for return values in a methodthat returns the set of all postive numbers. It's the latest AMD box so it shouldn't take too long, I don't understand it.".
"There is more worth loving than we have strength to love." - Brian Jay Stanley
The three items you seem to object to all have fairly legitimate uses in some computing contexts.
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
Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
The Theorem Theorem: If If, Then Then.
This was written a few years ago by a friend of mine . He thought it was a great way to express the business plan of the company we both worked for.
We often joked about using it in real work. Has anyone ever used something similar to show job dissatisfaction?
function develop (newIdea);
if (newIdea == yourIdea && newIdea > jorisIdea){
get (swiftKickInTheAss);
} else if (newIdea.mentioned (toJori) && newIdea != jorisIdea){
get (swiftKickInTheAss);
selfWorth = null;
set var (newIdea) = jorisIdea;
delete spine;
develop (newIdea){ ? (yourJob = CompanyName);
}
-Goran
Carpe Scrotum - The only way to deal with your competition.
This means that simple comparisons like $something != $something_else became way more difficult and contained completely usless comments:These were probably the most annoying comments I've ever seen. It only got worse with statements like ($something != $something_else && $this == $that).
What code like that tells ME is that something probably changed and I should probably find out why!
As opposed to the second example, which wouldn't alert me to possibly unmissed side-effects of that change.
When I'm writing in assembler and doing a lot of register juggling, for example, I'll usually put in-line commentary in the code describing the nature of the values I'm working with and the operations I'm performing (since that isn't obvious at all from the code statements themselves).
I also sometimes do that in older Fortran dialects since most of them are limited to six-character variable names, and since it's not always obvious what is being done.
Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
The Theorem Theorem: If If, Then Then.
An interesting thought in all this...
I'm slowly formalizing a philosophy that the most "control flow" should happen in a single file, preferably readable on a single screen. Difficult tasks should be delegated to appropraite API and/or objects.
We keep talking about "comment your code" but so many modern technologies (J2EE, I'm looking at you) try to do more and more "without writing a single line of code!" So in some ways we're set back. I guess you can "comment your XML file!" but it seems to be that there's often a disconnect.
SO YOU'RE GOING TO DIE: The Comic for Dealing with Death
The commentary should justify why the code needs to be there. If you can't justify it, remove it. But comments like
don't really cut it. The comment should explain what role this code has in the overall design. For example if you have a call to the fopen() function, it should be obvious that a file is being opened. But answer the question "why?" to make the comment informative.Of course, having good names for things can also help:now we need to go OSS in diesel cars
Have you ever considered the possibility that work came to India because it wasnt commented well enough the first time?
Welcome to the real world. Indians get your jobs because you cant do it well enough.
Its a sad thing that I bite the bait.
in a language as understood as HTML, comments are pointless. computer-generated HTML is also very nice. though the source may view source, if you want to decode it. perl::HTML makes it so easy to extract information from the perl-generated bbc website.
my fave comment in php is from blog-system Wordpress
"if you delete this line, the sky will fall on your head"
...has so many bugs in their code that they still work on it on a daily basis years after they originally wrote it.
Regardless of your philosophy about HOW to comment, I don't think anyone rationally can argue that code should exist without any comments.
We are the 198 proof..
Sounds pretty self-serving man. Why read your article when the classic "Code as Design" has already been written. Stupid noobs gotta do their homework.
It was hard to write, it should be hard to read.
Find coupons in Greeley
My job is to deal with unfamiliar code. I never read functional specs. I skip most long comments. cscope tells me most of what I want to know. I do rely on structure fields and flags having comments. The code I read has a change log; I read that too.
"Form follows function - that has been misunderstood. Form and function should be one, joined in a spiritual union."
Frank Lloyd Wright
Even when it's bad, it's still pretty good.
After being trained to take over two of my universities Intro to Programming courses, I was granted the almighty insight as to why the curriculum (and thus graders) require such innane comments all over the place in history's most inconsequential programs to date.
... at least from my university's perspective.
I'd have to wager that many of us found the process quite annoying... and it is. Especially so for those who already have a knack for programming. For these people, the intro classes only serve as an intro to the language the rest of the more meaningful classes use. However, for those who are less talented, or are completely clueless to the field to begin with the commenting process becomes very crucial.
In this case, the commenting becomes a tool for student and teacher/grader alike to assess how much the student understands just what it is they're doing. Unfortunately in most cases where the student is gifted, they feel it is just a mundane practice since they're commenting things that are 'obviously' obvious to everyone else... which actually isn't the case in the intro courses.
I've graded more programs than I care to think about where the program, while performing as requested, was littered with code that essentially did nothing. The use of comments allows teachers to understand why a piece of code was written by the student, and also acts as a preemptive remedy for useless code when the student realizes that a line of code he thought was needed, or had a hunch on, actually wasn't.
Past that primary focus of the commenting process in the intro classes, the object of commenting is very minimally for the purpose of developing good commenting skills for later use in collaborative projects. This is because, it is assumed that all future 'good' employers already have different standards for good commenting in place, and becoming a 'good' commenter, not to mention organizer of code, depends solely upon the framework your organization allows you to work in. In other words, they opt out of strictly teaching 'good' commenting in favor of a "Practice makes perfect" approach.
Also, I believe it is dangerous to assume what is obvious and what is not. If we compiled a list of what everyone thought every 'good' programmer should know, i would imagine the list of things would come close to an effectual "a good programmer should know... well... everything". Thus, it is safer to assume nothing.
Let me give you an example of what I mean. Lets say a VB programmer was the only resource on hand to tackle a project originally written in C by a very saavy C programmer... and this VB programmer had never written or read a single line of C to that point. Beside the fact that he would have to learn the language on the fly, many of the things that the C programmer might consider obvious would likely present themselves as huge stumbling blocks to the VB programmer. I mean... you gotta start learning somewhere.
That may be an extreme case, but I've seen it happen more times than one might think it could happen. The principle essentially holds when writing in languages otherwise not considered 'popular' at the time, or if you're updating old code that WAS 'popular' at the time, but no longer is... kinda like COBOL.
To reiterate in one last statement, "Never assume ANYTHING!"
To paraphrase Einstein: we should write as few comments as possible, but no fewer. The reason is that comments don't execute and therefore aren't constrained to tell the truth about the code. So anything about the code that can be said directly in the code ought to be because that makes what's been said inseparable from what actually happens when the program runs. If it can't be said in the code then it ought to be said in the tests. Tests don't force the code to conform to the properties that they describe but the do tell you if it doesn't. They are one step removed but still provable. The redundancy of saying the same thing in both the code and the tests is valuable because the difference in perspective forces a greater degree of precision and, therefore, a higher chance of correctness.
Saying the same thing again in comments is not useful from the perspective of correctness, so the value of redundancy in comments is limited to the value of redundancy in most communication: if it's done sparingly it adds emphasis, otherwise it's just a harmful distraction. The value of comments is that they can be used to say all of the things that couldn't be said in the code or in the tests. The best code expresses the vast majority of its important information in the code and the tests, but is not stingy about expressing all the rest of its important information in comments. Comments written in this way augment the code without distracting from it.
Remember:
Let me start off by saying that if you can't clearly communicate in your code, then you probably can't clearly communicate in your comments, either. The belief that one person would write obscure arcana with their left hand and interweave it with a plain-spoken interpretation of itself using their right hand strikes me as ridiculous -- they're either doing a poor job of making the obscure readable or they're not telling exactly what it does.
) ;
That said, the conculsion of the article is this:
"Good documentation includes background and decision information that cannot be derived from the code."
First of all, we call those "Business Requirements" and "Design Documents", not "Code Comments"
Second of all, I've yet to work with any Asian folks who would be able to not only make good sense of "We used a Byzan-Floritine quasi-macro here which allowed us to leverage the demo code we presented to management in June while maintaining synnergy with project Foo Bar [Update: Foo Bar got cut due to lack of funding; no time to revisit this decision.]" but then also maintain the code that goes with it.
That kind of comment neither particularly helps them understand the code ("My Microsoft Certified Training does not cover this Byzan-Floritine quasi-macro of which you speak.") nor does it do anything to help them take ownership of the code so that they stop calling me and taking up my time which our IT department deems to be substantially more expensive than their time -- which is why I'm not allowed to maintain my own code.
The comments that tend to go in my code typically start with "Here's where things get tricky about [bit of esoteric business logic]" or "Not the prettiest, but this actually works..." -- and we've got automated unit tests to ensure that it actually works, too.
The sort of code that doesn't get documented?
throw new ValidationException.Because(Reason.NumberTooSmall
Wouldn't you know it, those Malaysian support folks said that they liked how easy it was to read my code compared to the 4 other projects they were taking off our hands.
To paraphrase Einstein: we should write as few comments as possible, but no fewer. The reason is that comments don't execute and therefore aren't constrained to tell the truth about the code. So anything about the code that can be said directly in the code ought to be because that makes what's been said inseparable from what actually happens when the program runs. If it can't be said in the code then it ought to be said in the tests. Tests don't force the code to conform to the properties that they describe but the do tell you if it doesn't. They are one step removed but still provable. The redundancy of saying the same thing in both the code and the tests is valuable because the difference in perspective forces a greater degree of precision and, therefore, a higher chance of correctness.
Saying the same thing again in comments is not useful from the perspective of correctness, so the value of redundancy in comments is limited to the value of redundancy in most communication: if it's done sparingly it adds emphasis, otherwise it's just a harmful distraction. The value of comments is that they can be used to say all of the things that couldn't be said in the code or in the tests. The best code expresses the vast majority of its important information in the code and the tests, but is not stingy about expressing all the rest of its important information in comments. Comments written in this way augment the code without distracting from it.
Remember:
That would only work until people start doing what they basically do now and confirming that the comments are correct without actually taking the time to verify that fact. (Subtly incorrect is often much worse than obviously incorrect.) Granted, the system would remind the programmer to check, but a rushed glance at the comment will likely result in "yeah, it's fine" when it's not.
Last night, after posting the grandparent, I was thinking about that very problem, and thought that [for big shops with the resources to pull it off] extreme programming might be the answer here: The code and the comments are flagged as dirty after any changes made by the primary programmer, and can only be flagged back to clean after they have been cleared by the secondary programmer.
Again, it would require a huge investment up front [say $100,000 per programmer, and $100,000 for the ultra-cool database-driven document-management content-versioning system with the kitchen sink], but, down the road, it might offer some significant savings, in the form of more stable, more maintainable, and less bug-ridden code.
Ah. Would you care to port it to OS2200 then? The Unisys 2200 environment has no CVS port as far as I know, and it must be an easy task to do so given the flippant attitude in your response.
Right?
Or perhaps it didn't occur to you that there are a number of production *mainframe* systems out there that have been around for a very long time and that don't run on Intel hardware or use POSIX-compatible operating systems.
The whole world isn't UNIX and Intel, just the majority. But that doesn't mean that other platforms don't exist.
Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
The Theorem Theorem: If If, Then Then.
We are able to manage multi-million-line systems quite effectively without using tools like CVS.
:-)
All it takes is some sort of intelligent change management system, not necessarily source code management, and perhaps also some additional tools so people can quickly see the status of a given source module.
FWIW -- we often leave small blocks of commented code in the production source. Why? Because our internal customers have been known to change their minds in the past. Believe it, or not.
Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
The Theorem Theorem: If If, Then Then.
I've seen cases where a fresh from school programmer turned 20,000 lines of complex, hard to understand code into 3,000. The complex code was written by a programmer with 20 years experience. (Hence my belief that you cannot be both a good programmer and a good musician)
descriptive variable/constant names are good thing, they only are not sufficient, but a good thing none the less.
The snippett referenced above could be cooler by escewing the use of 'tmp' as a data element name... There may be some extremely rare instances where such usage is warranted. But in large, use of such names is somewhat akin to the use of profanity: the resort of the weak minded when they are at a loss for comunication tools.
Here's another go at it:
\//add elapsed time to fps accumulator and counter
current_update_time = SDL_GetTicks();
msec_since_last_update = current_update_time - last_update;
last_update = current_update_time;
fps_timer += msec_since_last_update;
fps_counter++;
maybe that's no %$#^* better
...then off shore the coding
we're doing it the other way around here and it's not working out very well (no, I'm not saying where here is)
Once I had to write a windows 3.11 device driver, so I downloaded the windows device driver developers kit (DDK) from microsquish... It was all 80286 assembler with the comments in spanish. I like assembler: it's not all uptight and regimented like c is, but I would have liked to have been able to read the comments. I was able to get my device driver written & working (& two years later a win95 version but I bailed on the win98), I'm not sure that it would have worked out as well if I didn't understand the example code but I did get the comments. I guess that's what being a PHB would be like.
it's been my observation that programmers that work in assembly are more disciplined and neater than those that work in oh, say VB or c# for example.
Now, it's harder to draw such broad generalizations about perl coders, some are elegant and others are, well... like a kid with finger paints.
Even the best self-documenting code can't tell you why it was written.
A good comment, by contrast, can answer the question, "Why the hell did he do it THAT way?" or "Now, what the fuck was I trying to accomplish when I wrote this?"
good programmer ^ good musician
Elaborate please. Someone is claiming the opposite view that musicians are more prevalent in the programming profession than elsewhere!
Try this with tabstops at mod-8, align all the comments:After your keystrokes, the s are aligned, but now the comments aren't. All this does is move the misalignment to another column. That's not a valid solution.
Anyway, it's this: Make as much as possible obvious from the code itself. And comment everything else.
It's not really about the volume of comments; it's about their content. You should usually be able to see the low-level of what the code is doing, and how; comments on that are not only superfluous, but their redundancy makes them actively dangerous when they don't get modified along with the code. What's usually much harder to see is the big picture: why it's doing it, and how that relates to the rest of the system.
As a result, comments tend to be more important at the top of classes/methods/functions/procedures than in the nitty-gritty, because that's where the high-level info fits. Literate systems, especially JavaDoc, are good at encouraging that sort of comment, but there are no silver bullets: it's down to the developer thinking about the code, and (most importantly) thinking about the poor sod having to maintain it in a few years' time. I think you really need to have been in that position in order to fully appreciate what comments should be.
Ceterum censeo subscriptionem esse delendam.
Actually, the French have a saying, "Never underestimate the bandwidth of a van full of backup snails."
the thing that separates human-written code from computer-generated code is that our stuff is readable to future programmers
Wouldn't that depend on who the future programmers are: men or machines?
Oh, say does that Star-Spangled Banner entwine / The myrtle of Venus with Bacchus's vine?
Thanks for the insightful mods, I guess public moderation suffers from "patriotic duty" amoung other things!? To the "flaming moderator": You can mod it down all you like, but it does not make it any less true!!
Those who come after you should only be able to find one or two contradictory, early drafts of the design document hidden on some dusty shelving in the back room near the dead 286 computers.
"But the designs were on display..."
"On display? I eventually had to go down to the cellar to find them."
"That's the display department."
"With a flashlight."
"Ah, well, the lights had probably gone."
"So had the stairs."
"But look, you found the notice, didn't you?"
"Yes," said Arthur, "yes I did. They were on display on the bottom of a locked filing cabinet stuck in a disused lavatory with a sign on the door saying 'Beware of the Leopard.'"
"Slashdot - News and Chat Sites Deviant". (Click "homepage" link above for details).
What an AWFUL article. As a maintainer of code I immediately read comments as though they were lies. The only useful comments are bug numbers or project identifiers so I can go look up the specification to match the pertinent code with the spec. Anything else is a junk comment. Heck, even the comments mentioning a bug number are lies.
The part about the search routine? You don't need a comment for that. "Oh what's this code doing? It's clearly called blah_blah_heuristic_search so I freaking wonder. We clearly have another function lying around called binary_search (that's how we know this other search is quicker -we previously profiled it). Let's try the binary search. OH it profiles slower. Let's stick with the heuristic search."
The article should be "Documentation is important". Comments are a last resort of a documentation strategy and Raskin even moves onto his real point in his conclusion. Why wasn't this his thesis?
1. KISS - and don't use acronyms like I just did.
2. Whenever you're coding something ambiguous or tricky, always comment as to how and why - this saves time later.
3. When declaring variables the first time, try to comment them and declare them in sections so it's obvious which are related - you can do this by naming conventions, but it's easier to read the comment.
4. Never assume it's obvious - if it's a long calculation, comment as to what it does (or that you think it does), so when it breaks or is changed someone (or you) can figure it out.
5. Don't use the number 5. You've made to many comments, so take a break and have a coffee.
-- Tigger warning: This post may contain tiggers! --
If it was hard to write, it should be just as hard to figure out.
I think the best and most important way of commenting is through version control commit messages.
That way, you attach the comment to the particular change you are making, and by looking at the history you can see exactly why certain lines of code are added.
It also doesn't clutter up the actual code where unneccessary.
And it doesn't have the problem that the code can change and make the comments wrong.
This is a good example of code that can be improved for documentation and readability, actually. Instead of checking for negatives, which is backwards to normal thinking, you can assume a combination will not work, and then describe the combos that will work:
/* Ensure arguments are valid */
/* make sure argument order matches the order
/* loop through each potion combination */
/* check that the potion combi is filled in
/* check if this combination matches the
/* this combination works. Use its
/* make sure we're not returning junk */
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;
}
If one doesn't understand binary, they are no programmer.. so I there's only one type. :)
There have been studies done showing that 4 is the optimal tab size for code. I think it could be standardised easily, at least in coding standards like GNU's. Of course, with in-code settings like VI allows, or IDEs that save their settings in a project file, it's not so much of an issue anyway.
You can use code in OS2200 and still use cvs.
How?
Well if you have a network you can save your files to another system and use CVS from that system. Do all your coding in OS2200 and then run a script that copys everything. You should look at CVS as a backup of all your code. I mean you do back up your code to something off that system right?
You can use code in OS2200 and still use cvs.
:-)
Perhaps. As I've said, though, the lack of such a source control system really hasn't been an issue with us.
I mean you do back up your code to something off that system right?
I don't make backups explicitly, no. The systems folks to automagic backups of all working files to tape at least once daily (active files are snapped two or three times), and there's at least one offsite backup of that information in addition to the local stuff on the tape silo here.
This isn't a PC we're talking about, remember.
Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
The Theorem Theorem: If If, Then Then.
Sorry, I was more referring to capability. I know some people that work on secured systems and are vary limited in how they can interact with other systems.
Anyway, having worked on a lot of legacy code; being able to jump through CVS and look at when where and why code was changed becomes vary useful. Like a good IDE it's not needed but CVS makes you more productive over time. Even though it has other uses being able to diff you code right before bugs show up with the code right after the bug shows up is enough to save you the few hours it's going to take to set it up and the 3-4 min a day it takes to use. Yes you can do this by hand but in that case CVS is going to save you time right off the bat as you don't need to keep lhe {}{JNK 05/05/05 - updated to fix error 2715} style logs.