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
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.
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
Comment removed based on user account deletion
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
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)
{
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"?
Yeah, good luck with that. Have a second career ready?
I once consulted on a large program that had been written in as convoluted a manner as possible, with few or no comments. The guy who wrote it used to brag about "job security". Well, when the company finally allocated a budget to replace the program, they not only fired the guy, but made sure that as many people in that industry as possible knew about it. He was unable to find a new job in programming, and last I heard, he was trying to sell cars somewhere down south.
You might have job security for a while, but it's gonna catch up with you.
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.
The only difference is that a lot of bugs are obvuous,
Yes, yes they are.
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.
It took a bit, but your comment is understood.
We will bankrupt ourselves in the vain search for absolute security. -- Dwight D. Eisenhower
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.
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.
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.
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."
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
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!"
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.
You. Are. Doing. It. Wrong.
If the code evolves, fix the comments. Unless you're deliberately trying to confuse the next person who gets the pleasure of maintaining your code...
Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
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
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
Beauty is only GUI-deep,
but Ugly goes straight to the code.
I prefer rogues to imbeciles because they sometimes take a rest.
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
I don't fully agree... however, I do think its sometimes true.
Often, one of the ways I know that my code is pretty good and well organized is that I find few places ... // setup the connection... // submit queries ... // check return values"
where comments would even be helpful. Often the comments just end up deliniating sections so I can skip to them easily "// check parameters
Of course, are we counting the comments that document what a function does? As I have been mostly playing with Java lately, the javadoc comments for documenting methods seem to be another beast entirely.
I was always a fan of the Linux Kernel coding style statement that if your code is too complex to be understood by a less than gifted high school student, then you should consider rewritting it.
-Steve
"I opened my eyes, and everything went dark again"
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?
Your code should be a narrative. How about
checkParamaters(...);
setupConnection(...);
submitQueries(...);
checkReturnValues(...);
The problem with this idea is that the actors in play don't lend themselves to a very compelling narrative. I mean, suppose I've got a data line that I've previously pulled low, and now I'm allowing it to float high - but I want to make sure it's actually floated high so I can be sure there's not somebody else pulling it low...
What is the data line's motivation for floating high? Apart from a current-driver driving the line high, I mean... Will the reader actually be able to relate to this conflict between two different slaves trying to assert different states on the data line? And, if we do make a narrative about this conflict, won't we have to explore the individual slaves' motivations for the conflict? Won't we need some depth of background information about the source of the address collision? Wouldn't the narrative demand proper explanation of the first slave's feelings upon learning he's lost arbitration, and condemned to forever remain in the shadow of the second slave? And what about the narrative of the second slave, who doesn't even know there was a conflict, because he's won it? These don't sound like very appealing characters to me...
Bow-ties are cool.
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.