If the Comments Are Ugly, the Code Is Ugly
itwbennett writes "What do your comments say about your code? Do grammatical errors in comments point to even bigger errors in code? That's what Esther Schindler contends in a recent blog post. 'Programming, whether you're doing it as an open source enthusiast or because you're workin' for The Man, is an exercise in attention to detail,' says Schindler. 'Someone who writes software must be a nit-picker, or the code won't work ... Long-winded 'explanations' of the code in the application's comments (that is, the ones that read like excuses) indicate that the developer probably didn't understand what he was doing.'"
An explanation may be long if it is explaining something complex that the code is doing. A long-winded comment may also be a precise one, rather than a general one: rather than an excuse, this may be an explanation.
-- IANAL, this isn't legal advice, and definitely isn't legal advice for you. Also, Squee!
Comments are good for many reasons:
1. Showing the next person what you were doing.
2. When you have to explain what you are doing, it helps you to discover possible errors in your code. Particularly logic errors.
3. It helps you if you have to come back and look at it in a few years so you will immediately have an explanation of what you were doing.
Of course for those of us who code perfectly the first time, they aren't really needed. :-)
Long-winded 'explanations' of the code in the application's comments (that is, the ones that read like excuses), indicate that the developer probably didn't understand what he was doing.'
Or that he's forced to work with people that don't.
Comments exist NOT to explain the existing code, but to explain all the other code that could have been written, but wasn't. They also point to things like test cases (which if your language doesn't suck, you can put in line), and explanatory standards documented elsewhere.
Don't piss off The Angry Economist
For me, it is bad spelling in variables and such. Or correct but "alternative" spellings - like honor_no_cache vs. honour_no_cache
Working with fellow students in a group (with one student being from England) brought this out, and in general poor spelling - category vs. catagory, etc.
Fortunately mostly fixable with find/replace, but still a bear to deal with.
Don't blame me, I voted for Kodos
* get_tail(node* list)
* gets the tail!
*/
Damn you racist filter!
you're doing it as an open source enthusiast or because you're workin' for The Man, is an exercise in attention to detail,' says Schindler. 'Someone who writes software must b
Comments do require a bit of effort and time commitment. If you are willing to spend time on the comments your most likely going to spend more time working the code itself.
The only times I find myself making excuses is when management didn't properly give the requirements or change the requirements to late in the game...so you have to make bad programming decisions as a band-aid until a complete rewrite can be done proper...just to meet a deadline that was shortened or a deadline that was insanely impossible because someone oversold your departments abilities...or a deadline that doesn't adjust to the new fangle features that were always supposed to be in there. Not everything is the prgrammer's fault in this world...in fact I think you'll find that very little of it is to be laid to rest at the programmer's feet. Expectations are high, pay is low, and management simply assumes cause there are teenage kids telling them they can write the same thing in shorter time means they know what they are talking about when they don't have the slightest clue...haven't coded anything over 500 lines of code.
Many people who write code are not native English speakers. it would be silly to expect their code or comments to read like a Thomas Hardy novel.
In addition, some of us write comments first and then fill in the code. Often, in fact quite often, the code evolves past what the comments say.
Someone who wastes time producing grammer-school perfect comments is wasting time that could be better used by making the code itself better.
Comments are for wimps.
"No matter where you go, there you are." -- Buckaroo Banzai
I sometimes write code for number theory algorithms. Often short-cuts and little speed ups have long proofs to justify why they work. If I expect the code to be used/read by other people I'll often include these explanations (and so I don't need to bother convincing myself later if I look at the code a year later). There's nothing wrong with long comments. Moreover, given a negative attitude towards long comments, many bad programmers will likely simply respond by not commenting their code at all. That's not good.
That's also why I don't comment my code.
It should be obvious what the code is doing just from reading it. If it isn't, then the code should usually be refactored. Comments are for explaining why the code is doing that. If your grammar is poor in the English then it's probably poor in the code too (unless you are not a native speaker). If you make spelling errors in comments then you probably do in code too. The compiler will catch some of these, but when you accidentally type the name of an instance variable or a global instead of a local, it won't spot it. If you're not checking your comments for this kind of error, you're probably not checking your code for it either.
Just as with online comments, poor grammar displays a lack of care. Hopefully, more people will be reading your comments than will be writing them. A little effort in writing them can save a lot of effort in reading them. If someone on the Internet thinks that their time is worth so much more than their readers' time then that just makes them an asshat[1]. If a programmer thinks his or her time is so much more valuable than that of people maintaining the code then he or she is a terrible programmer.
[1] I am fully aware of the universal law that means that, by writing this, my post will have a significantly above average number of typos. Please be nice...
I am TheRaven on Soylent News
NOT using MicroSLOP. I 'm sure you the know the intended reference.
Yours In Astrakhan,
K. Trout
This seems like a no-brainer to me. Sloppy people are sloppy and stupid people are stupid, how is this not evident? The only difference is that a lot of bugs are obvuous, when the code fails to run or runs is an unexpected way, while the bad comments won't stop the code from working, only from being understood.
There are a lot of times I'll see slashdot comments like "you might loose your mind" and I think "I hope that guy's not a programmer." Loosing your mind is quite a different thing than losing it, and like some software bugs might not be evident the first time the code is run.
Free Martian Whores!
Comment removed based on user account deletion
...see somewhat verbose comments than none at all. However, a good developer should be able to provide very clear and concise comments and let the code say the rest. I think this is what the original post's point is - of the code is not concise and clear, the comments won't be either. P
I used to fear clowns...but I'm discovering that chimps are far, far, worse.
English is not most people's first language. Be glad they want to write comments in English at all.
const int one = 65536; (Silvermoon, Texture.cs)
SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
That being said, we work in a company where virtually all code is reviewed. Long winded comments introduce maintainability issues, since the comment can diverge from the working in time. Extensive spelling mistakes in them certainly becomes irritating, especially since there are plenty of good editors available with spell checking included. That just points to sloppiness. Not bothering to use a tool's features shows no pursuit of excellence and that certainly places doubts on the rest.
!
Or at least sloppy thinking. I have no idea why this is, but as anyone who has looked at internet blogs can attest, the people who can't be bothered with proper spelling, grammar, punctuation or capitalization, or who can't differentiate between "loose" and "lose" are also (usually) the biggest idiots.
Please do not read this sig. Thank you.
Comment removed based on user account deletion
You expect computer people to know the difference between "your" and "you're?" Hah! Good luck with that. Most of the people I have worked with over ten years refuse to spell correctly or use proper grammar. If being literate was a requirement for employment, that could change.
Damping absorbs vibrations. Dampening is caused by moisture.
Yes, spelling and grammar in comments are important for understanding, and proper spelling in variable names in particular makes it easier for developers after you to follow and track through code. However, I disagree with the generalization that long comments always mean you don't know what you are doing. Most of my code comments are 1-liners, but I always leave long comments for function headers so everyone is clear on what the inputs are. I also leave larger comments for equations that aren't immediately obvious, ESPECIALLY if the equations are coming from spec documents. A spec number, section number and explanation help developers FIND these things later and actually understand them. Spec documents in particular can be thick and it's not always easy to see at a glance how things are supposed to work. Plus, if there IS a mistake (let's face it, no one is perfect), it's way easier to track where something went wrong if you know what the start point is.
...no two people are not on fire.
I always try to comment my code, but then the compiler keeps telling me there's no code to compile.
"Long-winded 'explanations' of the code in the application's comments (that is, the ones that read like excuses), indicate that the developer probably didn't understand what he was doing.'"
// This function kicks ass.
...
// This following code is like Chuck Norris. It doesn't know how to fail.
...
That's right, I'm an expert and I keep my code comments short and sweet. Observe:
function kick_ass()
{
while(true)
{
She's a hack who likes dressing like a man, man !!
I barely comment; JOB Security baby...
I do however keep a personal notes file of the few items I find interesting, or harder to work out; JUST in case I can't remember or tie together wtf I was doing.
~Mekkah
Two comments:
1. Comments are there to tell WHY the code is doing what it is doing, not necessarily what the code is doing. I deal with code all the time that has comments that tell me what I can easily learn by reading the code, but they don't tell me why so when it is broken I don't know if it is because there is a subtle problem with the code or that the developer didn't know what they were doing.
2. After literally getting headaches from reading code written by other people I came up with a simple metric: The complexity of the coding solution to a problem is inversely proportional to how well the developer understood the problem they were trying to solve. In other words, someone who understands the problem will have a simpler solution than someone who doesn't understand the problem as well. You can apply this metric to things other than code, too, but it is usually very apparent with software.
That's it! I'm making all of my comments ascii art from now on!
That was a long-winded blog post, which indicates he probably doesn't know what he's talking about.
I once coded a function that varied depending on what quadrant (+x,+y; -x, +y; -x,-y; +x,-y) it was in. I couldn't get it to work right in the second quadrant, but finally got it working by chance and said so in my comments. The code worked, but I didn't understand why and said so. Is that bad coding? It worked!
If you don't understand why it worked, then you don't know how it worked. Consequently, you have no idea under what circumstances it won't work. Unless your unit tests enumerated every possible set of inputs, you don't actually know it worked. Just because code works for some inputs doesn't mean it works.
Comment removed based on user account deletion
From 30 years of developing software, I've found time and time again that it actually does seem that people who don't know or care about the difference between "their" and "they're" are also too sloppy, unintelligent or just not anal enough to write clean, supportable and robust code.
However I feel we do need to make more allowance than the article's author did for people who did not learn English as a first language.
If comments even exist, then the code is ugly. Code should document itself.
(Any good Perl programmer knows this.)
Adidas To Bring Back Sneakernet
I work for a company in Serbia and we write code for an Italian corporation which also outsources their development to Brazil and India. I'm happy if comments are in English at all. Still, we get by just fine, as long as we agree on design patterns to use and writing clear and concise code. Also, whatever happened to: "Comments should describe what the function is doing, not HOW it is doing it"?
there are no comments? I was once a programmer for EDS - I was responsible for the UNIX API that back-ended our helpdesk system. It was mostly written in C. The single biggest issue I had were the contractors who we brought in who either didn't comment on their function libraries they wrote, or their comments didn't follow proper function header commenting that you get if you went to school.
The bottom line, if you don't have established code-commenting procedures and processes on how you code and a quality assurance process to ensure that code is written properly and documented, you get back what kind of 'box' you put around your programmers. Those procedures are not suppose to limit how you put smarts into programming, but establish common programming language 'parameters' all programmers use on your team. Beware of the contractor however, they tend to follow their own rules, and try to ensure their own self-worth by documenting poorly.
Management is doing things right; leadership is doing the right things. - Peter F. Drucker
Talk is cheap. Show me the code.Linus Torvalds
I am going with Linus on this one, not some tech author nazi.
I have found too often the comments says the code does X, and it does Y. What is even better is when the code is wrong. Just love it when that happens. I have had to go as far to prove to someone in the comments that there code was wrong to accept that there code was wrong, and he are grammar nazi too, so I say bullshit on this.
Programming is a art in itself, good coders can "read" the code. Comments are nice, but they are not end all, nor a guarantee the code is correct or good.Often it can be the opposite.
All I can say is "few anecdotes don't make data"
If the documentation is incomprehensible or missing, then the software generally wasn't well thought out or planned ahead of time, but rather just grew as an accretion of hacks.
This is particularly true of API documentation. I've even encountered crackpots in the Rails community who think that you don't need API documentation if you have unit tests; their code was abysmally unreliable, unstable, and performed poorly.
GCHQ Quantum Insert installed. If only our tongues were made of glass, how much more careful we would be when we speak
The group I work with views code commentary as a requirement of the job of the go-coder.
Initial development of a new method (procedure, function, whatever a discreet unit of functional code is called in your language of choice) begins with inclusion of a summary comment of the specification. This puts the spec where the developer is working and can use it. This comment block gets tweaked and resequenced to fit the logical and technical demands of delivering the specified result and to segregate each logical step into distinct comments.
Once functional code has been implemented and unit tested the comments are reduced or eliminated along side a focused and targeted walk through variable and method names to produce final code that is as self documenting as possible.
Comments remaining in the code are there as bookmarks/breadcrumbs, or provide insight into why a particular logical approach was taken. As for the variant spellings issue - we are a small shop in the U.S. so we tell our international employees that we use EN-US spellings. ("There is no 'U' in 'honor.' and it's 'aluminum' (4 syllables) not 'aluminium' (5 syllables).")
My office has been taken over by iPod people.
There are many coders who work in a country where the language is not their first language. Does this mean the code they write is rubbish if they make some spelling mistakes in the comments? And I've met at least 2 genius level coders who had serious dyslexia and you could hardly make head nor tail of their comments, but the code they wrote was superb.
This whole premise is just a joke. Next they'll be saying people who can't program very well wouldn't be good at writing any form of document.
There's a terrible irony in Donald Knuth feeling that it's an even more important development than TeX, yet outside of the TeX world, almost no one uses it:
http://www.literateprogramming.com/
William
Sphinx of black quartz, judge my vow.
... learn COBOL. Nice and long winded and "englishy". And an utter PITA.
If I have a long comment explaining "magic", 99 times out of 100 it's because I'm being forced to interface with a bad API which THAT CODER didn't properly understand. Glaring errors in the documentation, unexpected outputs, unexpected hangups ... these are my duty to comment about. Of course I don't understand why the API is malfunctioning ... it's a BLACK BOX. My employer might be too much of a cheapskate to purchase product support to troubleshoot the API. Or the vendor might charge outrageous support fees for their mess ups. I cannot switch to a different API, because I do not have the authority to make that decision.
My comments are self-defense when backed up against the wall. It does nothing to gauge my programming ability.
"Love heals scars love left." -- Henry Rollins
The granddaddy of WTF comments must come from the original Unix source, written by none other than Dennis Ritchie: /*
* If the new process paused because it was
* swapped out, set the stack level to the last call
* to savu(u_ssav). This means that the return
* which is executed immediately after the call to aretu
* actually returns from the last routine which did
* the savu.
*
* You are not expected to understand this.
*/
if(rp->p_flag&SSWAP) {
rp->p_flag =& ~SSWAP;
aretu(u.u_ssav);
}
So here's an example of a comment that does an excellent (I assume) job of explaining why the code is doing what it's doing, yet the whole thing is so complicated that Ritchie even needed to acknowledge that the comment probably wasn't going to be of much help either with an amusing, and now somewhat famous, statement.
Or it could be just an indication of a management failure.
A couple of years ago I was brought in to save a project that was hopelessly behind schedule and getting nowhere. Pretty quickly I got the idea that whenever I check something into CVS, it gets re-checked by a really helpful girl there, richly decorated with comments. (Now I do comment classes and methods extensively, as well as places where higher elven magic was used, but I do _not_ write stuff like that now I'm iterating through a node's children. If you need a comment to understand that "for" loop, then there's something deeper wrong with my code.)
But, anyway, stuff like a line that said "if (currentNode.isRootNode())" had been decorated with the obviously helpful comment "// when the current node is the root node". I'm still at a loss as to what extra info is conveyed by that comment, since just reading the code out loud gets you almost the same sentence and definitely the same meaning.
And it went like that for every single line. Every single assignment, trivial loop, etc, was dutifully duplicated in that line's comment.
Turns out, they were asked to comment their code extensively, and judged basically by quantity. So she was just abiding by the rules.
A polar bear is a cartesian bear after a coordinate transform.
Dennis Ritchie has a whole page of comments in the Unix source code, and what information they convey.
To maintain some sense of topicality: I don't particularly agree with the blog post. As someone with good English skills, I've read a lot of code where the English language skills (and thus spelling and grammar in the comments) of the coder are below mine, but their skills in the computer language at issue are superior to mine. Frankly, there's a far greater relationship between accuracy of the comments (do they actually describe what the code does) and the quality of the code, than there is between spelling, subject-verb agreement, and number of spaces after a period and the quality of the code. This relationship does follow the blog author's contention about coders needing to be nit-pickers.
Occasionally in my coding, I write a novel in the function header. Generally, this isn't because I don't understand the problem so much as its because I do understand the problem. I've spent hours or days understanding the problem, and the particular necessray function that implements the solution, and I don't relish spending hours or days 6 months in the future remembering what I know today. The interesting thing is that, most of the time, the novel is multiple times larger than the function - 50 lines of comment for a 20 NCLOC function isn't unheard of.
In my specialty (embedded systems, with especially tight hardware integration), there are functions that need to be written that deal with extraordinarily complex situations. Many times, the bare code tells a misleadingly simple tale - "do this, that, and the other thing", rather than (as Russ Nelson pointed out above)
but to explain all the other code that could have been written, but wasn't
. Oftentimes, the novel is there to explain all the ways to trip up in this 20-line function - e.g. unspecified hardware dependencies, subtle system dependencies, unobvious race conditions. Sometimes its there to explain why, no matter how wrong the function appears, it is actually correct.
And the worms ate into his brain.
What if the person who wrote grammatically incorrect comments is not a native English speaker? Engligh not fluent, C++ very fluent!
When a thief sees a saint, all he sees are his pockets!
I cut text from Finnish language websites and paste it in as comments. I don't know what it says, but it looks really cool.
I agree that a programmer must be anal about details, as one missing character can break your entire program. But, how you write your code matters, how you spell, does not.
If you think of your programing language as just that, another language, it doesn't matter how poorly you understand your native tongue, as long as you can 'spell' with the language you are programing with.
Looking at the tone of the comments is 100% different than looking at their grammar and spelling. It's possible to have disturbing comments in prose... But all that just gives you an idea that there might be something wrong.
I'm not a bird, I'm a super-advanced flying stealth dinosaur!
I don't comment on my code, so I guess that if the comments are non-existent then the errors are non-existent too!
Comments don't matter. I've been coding for 25 years as a consultant for hundreds of companies. All code is crap. The best you can hope for is to get home by 5:00 on Friday and do something that should really matter to you. Can I create effecient, nicely structured code? Sure - and then some minimum wage programmer from 'Elbnonia' comes along the next day and mucks it up - with no accountability. Do yourself a favor and accept these facts now - and you'll save yourself a lifetime of pain and disapointment. If you want to create something of quality, which will last - become a musician or an artist or a poet - or better yet - go and volunteer at a homeless shelter or food bank.
Everybody has their little "pet signposts" that they use to make wider conclusions. Although there may be small truths to some of them, relying on weak correlations is generally a dangerous way to make conclusions. Good programming involves a wide variety of skills. To focus on a few narrow factors does a disservice to this fact.
For example, I sometimes put in long comments because the business rules themselves are convoluted. Programming logic cannot make a silk purse out of a sow's ear. Ugly biz rules are ugly biz rules and are not explainable in just a few lines. It's outside of the scope of my duties to clean up the business practices (other than pointing them out sometimes).
I agree that long comments can serve as a yellow alert to stop and think. But that does not mean that all long comments are inherently a sign of flawed code. The author is being a drama queen via exaggeration. And perhaps it's part piety: I am a careful comment-speller, so you should be also.
Table-ized A.I.
Are you *sure* that's not Estonian?
Please do not read this sig. Thank you.
I feel that comments can be broken into four types:
http://74.125.93.132/search?q=cache:6l-STbmY0DkJ:www.gocomics.com/calvinandhobbes/1993/07/28/+site:www.gocomics.com/calvinandhobbes/1993/07/28/&cd=1&hl=en&ct=clnk&gl=us (sorry, Google cached copy because the website is weird)
CALVIN: "Dad, what's a control freak?"
DAD: "That's what lazy, slipshod, careless, cut-corner workers call anyone who cares enough to do something right."
CALVIN: "Am I in the presence of their king? Should I kneel?"
DAD: "If anything works in this world, it's because one of us took charge."
Good code should comment itself and when that is not possible clear and concise code comments should be entered. If the comments are difficult to read then it follows that the code is probably worse.
Its not hard for me to believe that someone who didn't take the time to explain themselves clearly probably didn't take the time to think the code through clearly either.
Commenting well in a program can be the difference between hours of backtracking, reverse engineering, and other wastes of time. Even if the original programmer is the only one who will ever see them, good comments are just as important as good code. I don't know about you guys, but I find myself having to go back to something I did months and even years ago. Comments make the total difference between a quick add-on/fix or hours of hair pulling frustration. Learn to Code, then learn to comment. That combo is unstoppable
I write my comments in my code for the person coming in and having no clue about anything but has to fix something. It can happen and I've had to deal with situations like that for code that had no comments or documentation. Comments are there not only to remind me months or years down the road what I did back then but also to help the poor soul who gets thrown in to the project because maybe something happened to me and I want as much info as possible not only in the documentation but also the code. For all I know something may have happened to the documentation as well.
~~ Behold the flying cow with a rail gun! ~~
you often wind up using certain functions heavily that reveal themselves to have strange quirks
since these functions are effectively black boxes that your average developer has no legal ability to understand deeper, you have to leave it at that
blaming the coder for being unable to know why something works in such a situation would be fundamentalist in attitude on your part
yes, you should understand everything you write in code, but you also need a job to put food in your mouth and a roof over your head. not everyone can be a greybeard learning the deep zen of a true coder in a completely open source environment
you should therefore show some leniency for the journeyman programmer trying to pay his bills, who has to work with black box functions under deadline out of necessity, not choice
in such a situation, it is perfectly reasonable to hack at the code until it works, then quietly walk away, unable to know why you made it work. in microsoft land, since the functions you are working with are closed source, you can't blame the programmer for this status quo
intellectual property law is philosophically incoherent. it is your moral duty to ignore it or sabotage it
I usually comment much more (and need to) when I'm coding drunk. That also explains the excessive use of the word "Fuck" in my comments. But even drunk, I know the difference between their, there and they're.
"The ferrets, they're every where I tell you!"
Frankly, morons like you are the reason the industry is laughed at by other, more formalized disciplines. Could you imagine what we'd do to a bridge builder who just tacked stuff on until it kinda sorta stood?
Easy on the self-righteous indignation. I'll stay with your bridge analogy.
The simple truth is there are few software industry segments written to your 'bridge building' requirement. You want maintainable software. Your boss wants maintainable software. At the C-level meetings, they want faster and cheaper.
Nowhere in "faster and cheaper" is there room for your mythic "formalized discipline." I'm not sure if you are after the kind of societal reverence a doctor or lawyer gets or what. If that societal respect is you want, get a JD.
Best case scenario, you are well-known and respected by your peers and the person to whom you report.
http://www.maxineudall.com/2010/02/should-economists-be-sued-for-malpractice.html
Any kind of comments...even poor ones are better than nothing. There is nothing more frustrating than having to pick through 2000 lines of code in a single method (inherited from someone) and try to decipher their "logic". Even having poorly written comments can help lead you through their though process, and assist in identifying the problem.
However, not everyone who produces software is a grammatcial genius. This is especially true of international developers having to put their comments in English for the American coroprations they work for. I've known brilliant developers from all over the world whose code was solid, but whose comments left a lot to be desired...understandably. I've never faulted anyone for attempting to make sense out of sometimes non-sensical processes.
This also doesn't take into account the frequent illogic steps "the business" want to put into software that developers have to compensate for. How do you comment an exception to a rule that, itself, is an exception to another rule that is an addendum to a clarification?
Shennanigans I tells ya!
My two favorites are: /* I'm better that you are */ /* If you can read this, you're too close */
I don't get it, if the grammar is wrong, how does the program compile?
Let's invent a machine that is based on mathematical logic, that can only interpret simple instructions, but executes those instructions precisely and with no ambiguity. Then, since human language is fuzzy and full of ambiguity (like human minds), lets invent languages that are extremely specific, so that it will be easy for us to tell our new machines what to do. Finally lets go through the laborious task of translating our fuzzy ambiguous thoughts into these rigid, well qualified languages...
...now we've accomplished all that, lets take all our hard work and undo it. Lets back-work a bunch of fuzzy ambiguous language over the well-specified one, creating a mish-mosh of two languages: logical human and illogical human. That sounds like a good idea, because what we really need is to say everything, and then say it again badly.
Commenting is highly overrated, and a lot of people have been indoctrinated by teachers that have little work experience. The adherence to code commenting stems partially from it being a first-pass attempt to avoid the shortcomings of a waterfall development process. Now we can do better. We prefer functionality over documentation. Well written code should be transparent to a seasoned developer. If it is not, see the two qualifications in the previous sentence. Commenting usually just mis-specifies what's going on, lets people get away with writing sloppy code, and encourages people to not read code that they ought to.
The main exception to the above is the documentation of API interfaces, which is really an extension of the concept of encapsulation. In this case, the developer really shouldn't have to read the code in question (though in practice one always winds up having to read a little).
I have no idea who this self proclaimed expert is, and as far as I'm concerned, her sweeping statements suggest that nobody else should either.
Go away!
This is my sig.
You can get all of that, if you pay for it. Most people would rather have features now, and never touch the code.
This is my sig.
Oh please. Inexactitude is *not* the same thing as not understanding why something works at all. We can build miles-long bridges *specifically* because we understand the underlying physics, and anyone who built a bridge without understanding the physics of why it stood under load would be drummed out of the industry.
I am assuming you refer to the modern physics that we are all so proud of. Let me tell you that in Europe, whenever you get a real serious flooding on a major river, only one kind of bridge survives with no bruises at all: Roman bridges. They are 2000 years old, but they're still up. The crap we're building today won't be up in 2000 years, I can bet on it. Look at the mess with the bay bridge, down twice in 50 years!!!! Ah ah ahah! Kuddos to modern engineering.
That would be because the Romans had some engineering, but not the equations we have today, so they over-engineered their bridges for safety because they knew they couldn't calculate the exact, optimal configuration for the expected loads and stresses. Over-engineering is a good thing if you don't have to account to the bean-counters. The George Washington Bridge across the Hudson River was also over-engineered because they didn't know the exact tolerances, and it has held up rather well.
---dragoness
So you are a good coder if you write short comments, like (?): //HACK !RG: code must work with decimals although it was never planned to.
hack();
Hey don't blame me, IANAB
Real Programmers don't need comments - the code is obvious.
"Here you can find the category of the word"
I'm sure somebody will try to correct me in that "hakea" actually means "fetch" or "search", but in this case I find "find" more appropriate. The word "avain" means "key" and it is probably related to explaining the idea of "category".
Escher was the first MC and Giger invented the HR department.
What are these things you people call comments?
Have gnu, will travel.
...but my comments are awesome.
Seriously, just look at all the +5 A.C. comments I post.
I've also heard (I can't remember where), "If the code and the comments disagree, they are both wrong."
The simple thing is a comment should be meaningful. A simple statement or a long explanation it should MEAN something to those who see it. If you write a long comment and it needs to be long fine, but if you write a 500 word essay that boils down to nothing (we all remember the school English assignment about the book we never read...) the get it out of there. No comments make a mess but so do long winded nothings. On that note I'll shut up.
One simple question regarding spelling/grammar mistakes: What about non-native speakers? Is their code bad just because he or she tends to write "recieve" instead of "receive" (just one example mistake that is quite common for native Dutch speakers due to bias by his/her mother tongue)? I would hope not... TFA goes as far as to claim that non-natives actually tend to have better English language skills. First of all, I'm not convinced of that as a general rule. But even if it were true, there will always be traps for even those people to fall into unknowingly. What's more, I myself most certainly know about "receive", but even so I get it wrong at least 75% of the time. I also know that due to "selective blindness" reading the comment afterwards is not enough to catch all of those.
At the other extreme: Back when I was still writing code on a daily basis, I tended to spell check it every so often and fix any mistakes found. Talk about bitf*cking... :-) But I fail to see why wasting time on doing that would be a guarantee of proper design.
Linux user since early January 1992.
I agree that coders should not be sloppy. "Ah the user will never hit return more than once" but outside of a mission critical application nit picking is a great way to never get anything done. The most successful companies generally have the approach of "Let's put some lipstick on this pig and get it out of here." While not being the statement of a careful craftsman it is what gets the bills paid.
Nothing sloppy about GOTO, it makes my code work :)
Why not just use wordpress & download some of their comment plugins like the Spell Checker plugin? We are looking to make the switch to this CMS for a number of sites (Cup of Comfort is one, which offers story review services, a cool ongoing story contest, and writing webinars).
Perfectly working, syntactically and logically correct code can be utter crap if it is not maintainable.
Years ago, a very smart man told me that I was not writing code for the compiler, I was writing code for the next poor slob that had to work on it. Let's face it, most source code is going to be subject to rework or maintenance over its life span, so let's do what we can to make that next developer productive. The key to this is reasonable commenting.
One of the best ways I know of to teach developers to write maintainable code is to have them do support and maintenance for a while. Developers learn quickly which styles work for maintenance, and which ones don't.
As far as I am concerned, source code needs to look good as well as compile. So I would go one step beyond TFA to say that style, indentation, proper symbol names, use of constants where appropriate, and (yes) proper commenting are all good indicators of quality in source code.
there are 3 kinds of people:
* those who can count
* those who can't
All my variables are single digits too. I try to keep method names no longer than 4 digits and I get a wood over cryptic package names. When you write perfect code you don't need comments or dumbed down names. It's just so obvious what is happening in the code.
FTFA:
If it's c++, it probably wouldn't compile, so it would get fixed, so yes, I need you to cite famous programming errors where that happened, because I don't buy it. Links or it didn't happen.
Remember - famous. Not trivial "example code".
When I get board and go looking for bugs the first thing I do is look at comments. Writing styles or signatures of the clueless developers on our team serve as beacons bugs are hopelessly beckoned to. Its not the quality of the comment itself but the person behind it that is most interesting.
Comments starting with "This fixes" sometimes have a tendancy of breaking other things or still failing to cover the entire problem space. Its mostly I believe those who waste space bragging about what they fixed tend to be noobies who to quote yoda still have much to learn.
Comments "blaiming the compiler" bring up imagary of smart little critters laughing at the dumb humans who can't squish them and always contain bugs.
Comments with profanity and insults are written by people who couldn't think their way out of an open window. They are also at risk of going postal at some point in the future. When you fix their code do yourself a favor and don't tell them about it. Use an alias when submitting changes to their work in your revision control system.
Comments with funny jokes are always written by genius talent. You should not waste your time and just assume the problem is elsewhere.
Comments with apologies (sorry..et al) are often a reflection of a bad form of laziness OR developers who have accepted that everything anyone will ever do is crap and persistantly strive to produce less smellier crap. Its a mixed bag - the bug load and realitve quality of such code depends on who wrote it.
Use of bad english, mispellings..etc I have never really found a usable signal in. It could be that english is not the native language of some or people rightfully want to get crap done and invest no time in spell checking comments.
A short description never hurt anyone.
I also find that if I am writing complicated code I like to write all the comments beforehand, and then fill in the specific jargon afterwords.
//Loop over every item.
//Preform some menial data manipulation if this is an existing item
//Do a nested loop if necessary
//Finish looping over items.
//Commit data.
It's like writing an outline before you write the story, which I find really useful in fiction as well. That way you know where you are going in the end.
Wait so because I write comments my code is there for broke. That's the most ridiculous thing I've ever heard. If the code has spelling errors in it could it be the the programming has bad spelling, or maybe bad grammer, which is turn would have nothing at all to do with there programming skill. for instance.
//Prints helo world
printf("\nHello World");
}
int main(void) {
I put a spelling error in there on purpose, well the code would work fine. What about being forced to leave comments for a prof to help explain the code. I really can never see how ugly comments lead to ugly code. Comments are a helpful feature of code if the programmer wants to put them in, they have no need to put them in and if the programmer doesn't want to they don't.put them in.
Complaining about the comments is like complaining about the indenting. So because the Identing is done using space not tab the code is broken? Of course not, Any one who's going to complain about people not writing comments of anything outside of the code are just covering up for there own lack of programming skill. Any real programmer will agree that comments are there for the programmer them selves to help them remember in a year or two if they go back to the code what they were thinking.
Weather the code is ugly or not has nothing to do with the code working, the code works or doesn't. Past that the code is only rated based on memory and CPU use, thats it, not comments, not identing or anything else.
Source code is a English (or human readable) language copy of a mathematical formulation. I have met a fair amount of very good programmers who had a very strong mathematical background but had very little strength when it came to writing.
Because of the mathematical background many comments were bad because they simply stated the equation (a + b = c as an example). Other times the author simply wrote a lackluster or bad English comment. In those example the CODE in question was superb.
My point, in summary, is that writing coherent and precise statements in any language is a skill. That skill is NOT needed to understand engineering or mathematics. Likewise, it is not needed to write good code.
Having said that point. Most people who write bad comments are usually not interested in the larger picture involved and seem to "cut corners" a bit to often. In my experience this leads to either bugs or a maintenance nightmare.
There is also something to be said about being a well rounded person.
###############
######## fUkc graNMar
###############
Read radical news here
I write my comments in swahili, if the comment was hard to write, it should be hard to read.
MMO Quests are like orgasms:
You may solo them, I prefer them in a group.
In the comments of the Sixth Edition Unix operating system.
I don't know if this is the right thing, but my experience is that I don't comment in general, no matter how complex problem the code solves, but when I recall my code, or go to debug something most of the time I find that I automatically commented something while coding if I was not sure or thought I should at that time to leave a comment there, so in that ratio I have very few comments on my overall code, but also I have had co-workers who ask "what the f**** is this ?" if something I wrote is not clear.
-- It is the mark of an educated mind to be able to entertain a thought without accepting it. -- Aristotle
// If it was hard to write, it should be hard to read.
where Caucasian niggers code stuff that works and for cheap. If it works they just move to next stage.
There are exceptions; timing-related software or analog inputs may be dealing with inexact bits, but basically everything you're doing with software is precise. Real-world building materials aren't. I once helped a crew of retired construction workers build a church, and not only did they use a lot less effort than us young guys (because they could hit something once, in just the right place, instead of waling away at it like we did), but they also had a lot of insights like "this board's a bit green, so as it dries it'll twist a bit _that_ way, so we should put it in this way up and nail it there so it stays in compression when it does that instead of going into tension.
Bill Stewart
New Fast-Compression-only CPR http://preview.tinyurl.com/dy575ks
The code you have to deal with actually has comments in it? That must be nice. The only time I ever encounter comments at work when having to deal with someone else's code is when it says something along the lines of /* I'm really sorry about this... */
The reality is that comments tell what the code ought to do; while the code only shows what it actually does.
I tend to write comments of varying lengths - sometimes, writing longer comments not for my own benefit, but for the benefit of the next coder - someone who may or may not have my understanding of the system or code; and more likely than not, either won't have the time to learn the code 100% in-and-out, or are not up to the same par. So sometimes, I will write a large comment block on an important thing in the code - so that they (whoever they are) will be able to understand it quite quickly. However, that is (as it should be) quite few and far between; sometimes documenting complex logic from elsewhere in the system that I have no control over but the programmer needs to be able to understand.
Of course, there is also the typical PHB managers who evaluate their programmers based on LOC, SLOC, and CLOC (LOC = SLOC + CLOC), and look for an even distribution of SLOC/CLOC - e.g. SLOC/CLOC = 1. In some cases that is good; but in most it is not.
All in all, you can't tell how good the program is by just general comments or comment analysis.
BUT if you are sloppy in your comments (grammar, spelling, etc.), you have probably been sloppy in your code. To that end, I do very well agree with the article.
P.S. BTW, I've been in 3 positions where I have replaced people. One fired; one died; and one quit. In two of those three, the original developer was no longer available for inquiry; in the third, it was possible but not easy and only for a short time after he left.
Truth is like the sun. You can shut it out for a time, but it ain't goin' away. - Elvis Presley (source: imdb.com)
"You" - who formally prove your code, comment it, and make sure it works right - are called at 2 am in the morning to fix code that "He" wrote. "He" is now your boss, because:
Programmers beware: the meticulous, but correct, programmer is a valuable asset to the company; the sloppy but fast programmer is his boss.
The society for a thought-free internet welcomes you.
Worst: Originally erroneous or out of date therefore erroneous comments. Actively destructive to comprehension of the program, and once detected, causes all other comments in the program to be rejected as untrustworthy and worse than useless. "Comment Bug".
2nd Worst: No comments - indicates the developer either does not understand the purpose or method in their madness, or is lazy and sloppy. Either is very bad.
3rd worst: Redundant comments: /** Gets the Foo! */ Foo getFoo() See Java api documentation for prime examples.
I would much rather read a long rambling philosophical comment that was essentially correct and did add some information than to deal with any of the above slackerware.
Where are we going and why are we in a handbasket?
Comments are a skill in and of themselves, which a whole lot of people never master.
I remember two people who worked at a place where I was programming. The first
was a woman, freshly out of school who was taught that comments made the code.
So she dutifully wrote beautiful comments on the theory of what the function was
going to do, but also inline, especially for arcane things going on in an algorithm. All
nicely spaced, neat. A marvel to behold. Problem was, the code this person did
had some form of overflow condition (this was C) about every five lines, such that
I knew if I poked at the code from a higher layer I could cause problems. And did,
because I was trying to force the issue and have some kind of review go on.
The other person in the larger group was a 20ish male, who saw human interaction
largely through the eyes of TV, and gaming / nerd get-togethers. Hardly a bad person,
he just didn't seem to have humans around him when growing up (more than a trifle
odd, even now--I met him again for the first time in 20 years; the only change was
gray hair). He was one of the people I'd go to for help when I botched things, or
wanted comments on an idea I had. His code often worked the first time run, and
I'm not talking of little 10 line routines, but larger complex functions. His comments
were about the opposite of the code, both in terms of spelling, grammar, and that
ephemeral concept of how to communicate in general. Some sentences were
better read thinking of them as RPN, and others simply defied standard logic.
Comments that did survive that minimal test of English were often spelled in
novel ways, causing euqal parts of head scratching and laughter. But the code
was great!
I offer these two examples which while extremes, are examples that poke holes
in the idea that there is a common relationship between comments and code.
Certainly some people will fit that mold, but I think that more random than not.
Comments are a sign of bad code. That's because the more comments you have, the more errors you have in your comments. Uncommented programs have zero errors in comments, which points to excellent code.
Naw, you've got it backwards...
See, any given block of code is bound to have a certain number of errors - say, at a rate of 2 errors per thousand characters. The comments don't really impact the number of errors you'll get in the code itself. If the odds of any given program byte being in error is "r", and the length of the program code is given by "s", then the number of errors is "r*s" - so the only way to minimize the number of errors in your program is to make it as small as possible!
Bow-ties are cool.
Syntax is like English grammar. The vocab of a computer language is much smaller than that of English.
That you need comments to read syntax is like saying you need comments to explain the english in a book--which are typically footnotes and sparsely used. And that's the way it should be--write comments only if the code is unexplainable.
The only time I see lots of footnotes in a book/article are in scientific papers--which are typically explaining someone's crazy spin on how the world works.
When the deadlines get near enough, you may be faced with a choice of using the somehow-not-broken code or miss the deadline. Been there, done that.
But at the same time, I recognize the dangers and I'd rather not work that way. In short, unless I got a manager breathing down my neck who jacks up the pressure, I take the time to do it the right way. And in the long term, it usually pays off. Because intransparent and poorly understood code will pile up to the point that no one understands it anymore.
C - the footgun of programming languages
The real reason who those bridges are standing while the Bay Bridge keeps going down is called "cars". The Bay Bridge is under much greater load than any Roman bridge ever was. Tectonic activity in the Bay Area probably doesn't help either...
Wait... I'm confused... Is this a car analogy or not?
Bow-ties are cool.
I sometimes comment my code in excruciating detail. But that's when what I've done was so hard to figure out in the first place, I want to make sure that whoever comes after me or if I have to revisit it again, there's some explanation as to what the hell's going on.
XKCD:Xeric Knowledge Comically Dispen
The range of views aren't exactly shocking, somewhat upsetting at times though.
Comments should explain the intent in clear language, in my career I can't count how many times that helped someone else fix a bug in a domain that they knew very little about. Yes, the code does what the code does and comments may not be consistent with that but they should and those inconsistencies are defects. Really good code doesn't need a lot of comments but what about the domain knowledge? Is there any chance you'll bring someone new to the team that doesn't know the domain yet and want them to work on bugs? Is there any chance that the domain might shift?
As to the correctness and the effort put in to comments, it's just another indicator, is the author of the code a hack or a craftsman? Shit, modern IDEs even have spell checkers builtin for comments, it's not that hard. I've struggled with it at parts of my career, we have this pressure to work fast to get things done quickly and especially in American start-ups we want to skip the bullshit and get to work on the real problems we're trying to solve. It's this hacker culture thing that has been created, you hear legends about guys that coded all night and how they wrote xyz in a month of 7 day work weeks and so we think that the LoC count is what matters. As a result, I've seen giant complicated programs with minimal comments, I've seen labs with just complete messes of wiring, tons of other things ignored, install and upgrade processes completely ignored because "that's not coding"... all these roadblocks that are created that eventually prevent a team from being really agile and quick. Basically, if you do a half-assed job at some things, you'll probably do a half-assed job at others and it's just a matter of time before that affects the product. As a software engineer, doing a half-assed job at things that touch the code is terrible, at that includes comments. It's better to have good comments and not need them than it is to not have them and need them. It's funny, everyone who has written code has spent time fixing some small one line defect, you know an off by one or something like that, and it's stupid and easy once you see it but that didn't prevent it from being written in the first place. You cna't be a perfectionist and do everything perfect but what things do you want to half ass and who do you want it to affect?
It reminds me of another saying someone told me a long while back. Cars don't have brakes so they can go slowly, they have brakes so they can go fast. It strikes me that if you don't have time to write a few lines about what some method or class or function intends to accomplish in plain English, you've got some other problems. You need to pump the brakes a little. You can code as fast as you want and cut out keystrokes and, clearly a bracket is much less time consuming that "BEGIN" but at the end of it all, can you speed up the thought process of architecting good software? I'll do them one better, coders that don't comment usually aren't architects and usually aren't nearly as senior as they like to think they are. I don't think it's universal but I've seen at least a couple cases where they were difficult people to have on teams, they simply didn't like to work with others and probably spent more time defending their turf or jobs than building killer products. Sure they can code, but I usually want something else on my team, there are a whole lot of guys in China and India that can code...
Some of the finest code I've ever worked on was uncommented. Some of the worst code I've ever worked on had terse, but informative and readable comments.
This smells to me like someone who didn't work with very good code becoming aware of the fact that their initial assumptions about comments were incorrect. Sadly, they have yet to discover that their second round of assumptions is just as invalid.
If you ever want to browse through some solid code in order to get an understanding of what good code looks like, I suggest GCC. Just one example file (gcc/alias.c) starts with a comment on line 50 which continues to line 129, and I assure you that it's not there because the person who wrote it didn't understand what was going on.
I just recently wrote some API documentation guidelines for our developers. You might want to check them out (click "downloading" link) if you are interested.
Feel free to comment, I'm sure some points in the guidelines may be questionable. There's also a handy reference card (click "downloading" link).
I usually write a code comment and then discover that I should move the code under the comment into a separate function anyway, either for readability (e.g. of page-long loop) or re-use, so then I can shorten the comment to a function name and live without the comment.
Long or copy-and-paste generated comments often suck, because like code, they tend to rot when not maintained properly.
Comments describing method "contracts" are usually the most useful, while comments of the kind "parameter: Integer result - the result" are not very helpful, even when they cover every method.
Hey don't blame me, IANAB
I once mis-spelled the word "fogger" by typing "flogger." I hadn't realized it until a co-worker need to port my code to another application. We left it as flogger simply for amusement. The code worked properly though.
Praying for the end of your wide-awake nightmare.
You wouldn't happen to code in Perl, by any chance?
Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
You wouldn't happen to code in Perl, by any chance?
Hey, the math speaks for itself... What can I say?
Bow-ties are cool.
I have a bunch of witty and spiffy comments to make on this, but you summed it up quite nicely. I should just move to the next article - haha.
I don't comment my code at all ... does that mean it doesn't really exist?
That is not the fault of the practice of commenting code. That is the fault of lazy-assed developers who don't maintain the comments.
If the practice doesn't work in reality, it is not a good practice, regardless of whose "fault" it is. Fortunately there are better ways to achieve readable and maintainable code.
The usual way comments are used is to write crappy code, and then add comments to explain it.
This is analogous to using perfume to cover a bad smell. It kinda works, but it is much better to get rid of the stench in the first place. Translated to programming, that means that you should work hard to make your actual code readable. That means good naming, but also good general design. If you can't find a good name for a class or function, that is a clear sign it should be redesigned, probably broken up.
If you do this well, there some things will still need comments, and for those you should by all means do so. But it is probably 1-5% of the typical "well commented" code base. In code like this, when you see a comment, you will actually be interested to read it!
This way you also have no need to apply the strict discipline that you talk about of always updating both the code and the comments, and there is no risk that they get out of sync. All that energy and effort you have to spend doing that can then be redirected to more productive efforts.
10 PRIN "WTF" ...obvuous... ...or runs is an unexpected way... ...There are a lot of times I'll see slashdot comments...
SYNTAX ERROR
SYNTAX ERROR
SYNTAX ERROR
SYNTAX ERROR
Glad I don't comment.
I want to play Free Market with a drowning Libertarian.
Real-world architecture, engineering and construction is designed around those measures of imprecision. There's a reason the architect specifies a dimension to be 3' 0" and not 3.000 +.000 / -.005. Saws aren't that precise. Tape measures aren't that precise. Carpenters aren't that precise. So the architect leaves trade practices to make up the difference. Instead of trusting the lengths of the boards are exact and will make the walls perfectly plumb, he uses a level. Or since finished wall boards never actually touch the floor, he covers the gap with trim boards. That permits expansion and flexing without cracking the walls. As a result, your house is nice and straight, and yet it isn't "brittle". The trim boards at the interfaces better look nice and fit nice, even though the ragged edges they cover are certainly rough.
Software can be designed and built the same way. Typeless languages are one method, and exception handling is another. Encapsulation is all about hiding ugly details behind a precise interface. Design by Contract is one way to ensure the interface itself is precise, regardless of the code behind it.
They still have to be "pretty close" to be acceptable. A 2x4 can't be completely twisted like a corkscrew, nor can a floor be a bubble off from level. You can't use a 2x8 when a 2x10 is specified. Likewise, your calculations still have to work. But if your calculation is almost instant 99% of the time, and marginally slow but still OK the other 1% of the time, it might be good enough for your application.
At the end of the day, software interfaces better look nice and fit nice and do their jobs. But the internal workings of the tasks can be ragged and yet still function effectively (most of the time.)
John
You should at least comment your code, such that the next time (3 am) someone (you) is looking at your code you can make some sense of it.
Whoever is criticizing grammar in comments obviously never had to look through legacy code and ask him/herself "WTF was this developer thinking?!" Or better yet, looking at one's own code written five years earlier and asked him/herself "WTF was I thinking?!" In those cases, any comments at all will provide clues.
We should be encouraging coders to use comments _at all_, not giving incentive to shortchange it because they are going to be graded on stuff the compiler ignores. Any coder stuck with making changes to old code will be very thankful to see long-winded comments.
Let's not forget that code is read many more times than it is written. Yes, it would be nice to have precise comments that tell all. But if a coder wants to go into detail then friggin let him, to suggest otherwise is just dumb.
Real men don't comment their code. They put it on ftp and let others create a wiki for it.
UTF-8: There and Back Again
Yeah its funny but the more someone doesn't agree with my point usually the worse their own code is.
Are you listening to yourself? "If you disagree with me I'm going to assume you're a lousy coder". How am I suppose to argue with that exactly? Submit code to you for a code review? Clearly this is a comment from someone who'd prefer character assassination of someone they'd never met to actually refuting or counter-arguing.
I guess yours must be pretty bad, not that you would ever see it yourself.
Your argument style is the height of irrationality, and it's pretty clear you have zero inter-personal skills. With such a poor command of logic as you've demonstrated with that, I'm not convinced I'd want to use anything you wrote either, but at least I'd have the common courtesy of LOOKING at and evaluating your damn code before making such a rude obnoxious comment.
FYI I have had some fantastic feedback on my code, and I make a pretty decent living at it. So what do you think I'm going to care about? The ramblings of a stranger who's never seen my code here on slashdot or my performance review and pay cheque.
It would have been much more concise if you'd just said I had cooties.
These posts express my own personal views, not those of my employer
So what your saying is if I don't comment my code at all, then by definition it must be genius?
They've stood for greater than 1,000 years. Do you think they fully understood all the physics? HINT: No, they didn't.
Over-the-top Response Guy! Giving "Over-the-Top Responses" since 1970.
Hmmm.....that sounds a lot like "Evolution". Maybe the I.D. folks should take note.
Over-the-top Response Guy! Giving "Over-the-Top Responses" since 1970.
_script_ in Perl. ... Perl is as much a programming language as is html.
And Perl coders are as much programmers as MCSE's are engineers.
public static publicstatic(int main) {
label:
long long long_number = 0;
for (int inti=0; inti>0; ++i) { };
long int integer = 0;int sky_is_green = sky_is_blue= 0;
if (long_numer!=80) {
if ((long int) long_number==integer && sky_is_green!=~long_number) printf ("hell");
if (!sky_is_blue) printc('o');
else print ("my god!");
printc(" "); }
else if (!sky_is_green!=sky_is_blue)
goto label;
else
printf("there");
printf("world!"); }
I think the golden rule applies here; do unto your code what you wish your predecessor's had done to their code. If you write your own code, maintain it yourself, and never have anyone else work on it, then do whatever you want. Heck, use no punctuation, indentation*, or even carriage returns if you can help it.
However, there seem to be two camps; those who see the value in comments, and those who don't. Comments wont detract from those who don't like them (besides more trivial annoyances like wasted screen space), while the lack of comments may significantly hamper those who would appreciate it. It seems safer & more efficient to comment and make understandable code accessible to all, instead of saying that "good programmers" shouldn't need it, and raise the requirements unnecessarily for the maintainability of your code.
Used properly, comments can help. So just find a helpful way to do it. My mindset is that I write for the next guy, assuming that someone's going to hand him the code with an explanation of what he should be doing, and the comments will help guide him. They help the same way as chapter titles. Chapter titles are unnecessary and often can be completely removed without altering the story. But try to skim through a book and find what you're looking for w/o titles, and it's a pain.
I just jumped into an existing project that a genius (really) friend of mine started. He's very smart, but not as experienced a programmer. And the #1 pain point right now is lack of comments. Some of the code is plain spaghetti. That's fine, I'll just refactor it. But since there's no comments describing *why* it's doing what it's doing, I can't yet refactor.
Other things work just fine. But again, lack of comments prevents me from understanding what it's doing without understanding the entire context of the entire system. This is bad design, but that's the point - perfect code may not need comments, but none of us need worry about that (since we wont be working on perfect code anytime soon). It's not a crime to have rough code because the system is still organically growing. It is to have tons of uncommented stuff jumbled together.
Help me to help you. Help your successors maintain your crap. Comment your code. Make things easier on people (I'll put a 1 liner describing this section, since it's a little tricky), rather than harder (Really smart people will understand this, and I don't care about the others).
* Python users: find another way to obfuscate.
Natural language runs on human brains. Programming languages run on processors. The structure of the two different kinds of hardware differs so greatly that the only similarities are at the level of analogy. So you cannot draw useful conclusions about a person's use of a programming language from the way they use a natural language. In any case, someone who uses the term 'grammatical error' in the sense used in the blog post doesn't have a sufficiently sophisticated understanding of natural language to issue pronouncements on any related matter.
As a dyslexic I resent the idea my spelling is related to the quality of my code. Maybe because of my dyslexia, I have feelings about over commenting. If you want to write a book, write a book, but don't write it in your code! What I can't stand is when I can't read the code for the comments, or when the comments are wrong or pointless, i.e. the variable/function name tells you already or code and comment don't match. You end up with two sources in the same file, one real one, one for humans, why not aim for one for both? Two is asking for trouble. If you must write a lot of comments, please put it above the function so it's out the way. I feel software is organic, it evolves, it's farmed as much as designed. It quickly gets beyond what we can design. By trying to formalize it, you're sucking all the joy out and slowing down development and removing the creativity. There is a balance, you go one way it's crazy bat shit, you go the other and is slow and everyone leaves for something more fun because life is too short for such drudgery. Write as clearly as you can, comment where it's needed, automate what testing you can (without slowing everything to a point both users and developers get frustrated), then test it on as many users as you can. We all use programs written like this. I've never even seen this perfectly commented code ivory tower types rant about. If there is an open source example please point to it so I can see it. What I see if that when people first start programming, or start in a new language, they comment a lot, but that dies off as reading the code becomes easier. The other group who comment a lot are ivory tower types, and some are good, some are bad, so I don't think it helps them. I would rather good code without comments, then bad code with lots of comments.
I tend to document my algorithms in the code. Even if the code is fairly straight forward, the comments explain what the code is *supposed* to do which simplifies the process of development and debugging. I tend to briefly describe the purpose of functions and document their inputs and outputs. It saves a lot of time when I revisit old code or share my code. It takes a lot of effort to fully comment the code and I think programmers who don't do it are just lazy. I've downloaded a ton of open source software in the hops of helping to debug or enhance it. Virtually without fail, every project I have ever seen is completely without documentation or helpful comments. It's as if somebody wrote a script to strip the comments out of every piece of code checked into the repository. I find that extremely frustrating. Even if the code is obvious and as simple as can be, there are still dozens of files to examine and commit to memory. "Was that the print function in m_system1.c or a_systemb.c ? Who the fuck named these files? " A person's code is sort of like the county's 10 volume book of codes and regulations, or the legalese on the bottom of a contract, or my health insurance provider's explanation of my benefits. Sure the words and sentences are clear enough to the person who wrote them, but the rest of us need judges, lawyers, and agents to give us the Cliff's Notes version. Code needs comments. I do believe that the effort that goes into commenting (or lack there of) is a reflection of the programmer's professionalism. And in the case of FOSS, I think it would be a lot easier for the public to contribute and for the project to change hands if the original programmers could swallow their elitist pride or crawl out of their own heads for a second and actually write some comments at all.
Seems nobody else is getting this. Sad to see that nobody made this comment already, and sadder still to see you only at +3.
Good comments documents WHY.
I lost my sig.
Which is why I prefer reading Meta comments over comments that tell what said code is doing. I can tell what the code is doing just by reading it. In any case a quick comment at the beginning is enough. What really comes in handy later when fixing bugs or adding features is Meta comments. These are the "Why" did I do it that way comments. These comments explain why I'm using a certain structure, variable, etc. They explain what I was thinking at the time. Why did I do it a particular way. That reasoning may or may not be wrong later, may be able to be improved, but it gives me a real reason to re-write said code or leave it alone. i.e. It explains why if change this particular bit of code, I need to plan on changing a lot of other code as well.
An idiots argument. /* This is a for loop */ /* This here fer loop calls DoSomething MAX_INDEX */ /* times to init all linked elements to array dependents. */
I feel dumber having read this.
If its false for one case its false for all...hey look below a false case.
Yeah OP marked as a twit.
if (a == b)
{
DoSomething();
}
for (int i=0; i MAX_INDEX; i++)
{
DoSomething();
}
In Python, long comments are necessary in any public-facing code.
:type: and :param: descriptions :rtype: and :return: descriptions
1) Due to the dynamic duck-typing, the docstring is the only place where you can explain to the world the exact structure and conditions of each parameter and the return value, especially if you are returning a dict that maps pairs of records to vectors.
2) The docstrings are where you put the doctests, which form an executable mini-unit-test and mini-tutorial for every public API. doctests also mean you have to write the code with few explicit dependencies (or spend most of the test lines mocking them out).
A 4-parameter public API function easily needs:
1 line (maybe 2) for description, followed by 1 blank line
+4*2 lines for the
+2 lines for
+5 lines or more for the >>> doctest lines
>=17 lines of comment per such function
My experience and its fairly vast as I have seen millions upon millions of lines of source code is that well written code requires almost no comments. If you have to write very many comments then one of the below is true:
a.) You don't have a requirements/design document and your comments are the design.
b.) You don't understand the problem well.
c.) Your using a overly complicated piece of code.
d.) Your code needs to be broken down into smaller functions/procedures.
e.) You are magical and create numbers that you insert directly into your code.
f.) You like to write comments like "This is a for loop"
My baby birds often start out writing massive amounts of comments when right out of school, but then they work on their own code 6 months later and come to the realization that the big comment blocks explain the obvious mostly and hide the context of the code. At the same time they work on code I have written with only small amounts of comments and find they actually understand my foreign code better than code they wrote themselves.
People who insist on allot of comments usually are destined to be managers as they are poor coders. Think of it this way. THEY are the ones having a hard time understanding the code, so THEY want more comments. Problem is...you add the comments and they still do not understand. Meanwhile nobody else is having a problem other than the self appointed comment czar.
Still code, in a general sense. Non-literal representation of what you're creating. Anything that isn't WYSIWYG is some form of a code.
Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
For what it is worth (especially this late in the game) the quality and type of comments added to the code is a combination of several factors.
1. Number of expected eyes. The more people that I expect to see it, the better the comments need to be.
2. Length of development time. The longer the code takes to write, the better the comments need to be. For some of my personal/hobby projects that have lasted for months or years, I was lucky to find 20 minutes a day to work on it. Adding comments to the code was absolutely necessary so that I could get stuff done.
3. Code complexity. The trickier the code, or the more modules/files that impact the code, the better the comments have to be.
4. Prep-work time. The longer it took me to figure out what I needed to do (and why), the better the comments need to be.
Re-reading through this, the longer I expect the code to be around, the better I expect it to be written and commented. I don't want to waste time trying figure out both the intent AND what the code is actually doing. Nor do I want others go through that as well. The better the comments in the code, the faster someone else can get up to speed on the code I have written, which means that it costs the company I work for less $$$ down the road.
When writing comments, I try to include ...the 'why' where applicable, and what it is supposed to do, and on the complex code I state
1. The INTENT.
2. The 'WHY' where applicable.
3. Expected state information at various locations for more complex code.
Readability is a must. If it is not readable, then from my position it is flat out wrong. If it is not readable, you (or someone else) can not know if it is right.
Except of course if you are coding in an MS environment where the work often IS the work-around. Try writing some code to replace template items in a word document using search-and-replace and you'll find yourself writing a long comment about why all the cases are required to deal with the anomalies of what is considered a "word".
This reminds me far too much of a Major I had in the Air Force that would spout off statements like "Shiny shoes make the missiles fly better!". Sadly the First Shirt was a political climber already known for citing technical definitions like "May means Will" in maintenance procedures to enforce completely unrelated things like "Posters in barracks may have a trim applied", and was happy to accommodate this imbecile.
Within six months we went from one of the Air Forces best flightlines to being concerned with BS stuff *all* *the* *time*. Maintenance didn't get done as fast, or as well - but hey, we had wonderful 'Team Building' Exercises among the newly promoted people with shiny shoes while morale circled around the drain.
None of which is to say that neatness isn't a valid skill to develop doing maintenance, or that good commenting isn't a good skill to develop in coding. But there is a style of failure I associate with over-emphasis on either.
Pug
An Invisible Entity of Vast Power whose existence must be taken on faith alone: Liberal Media
Well, they're recognizing the symptoms, but missing the point completely.
It's the typical IT professional's misconception: "I'm using computers, therefore my skills are based on mathematics."
No, no, no, no, no. A programmer is a linguistic being. Mathematical skills are most definitely a plus, but in my experience, the most gifted developers are the ones who are also able to express themselves verbally and in writing, and who understand the difference between the thing and "the thing".
Mastering a programming LANGUAGE is different to mastering a human language only in that when programming, you're actually CREATING a language. The levels of abstraction are immense when you know what you're doing, as is the power, and really - if non-geeks like Heidegger, Foucault, Berger and Luckmann had the tools back then that we have know, they'd been friggin' ecstatic!
You want a good developer? Look at how the resumé and application are written and constructed. You can sort out the first 90% of crud right there. Find someone who knows how to express himself or herself concisively and correctly and you have a starting point.
(Btw, I'm Danish, so I know my English is crap ;) )