Successful Strategies for Commenting Your Code
LilG writes "Over at Particletree, Ryan Campbell writes about Successful Strategies for Commenting Your Code. His essay gives advice and examples on proper commenting, and details some different strategies."
These comments you speak of, they seem foreign and strange to me.
indeed, that's the problem
-- marc
I was doing some maintenance on someone else's code and came across this nasty set of like 8 nested if/elses. It was a bloody horrible hack. But the best part of all was the comment right at the top: /* Oh, fuck */
-- (Score:i , Imaginary)
Don't EVER comment your code if you work for a company. That's a sure fire way to lose your job! If you don't comment your code then you are the only person who can understand it, making you indispensible.
In summary, DON'T COMMENT!
it should be hard to read!
but not really, commenting as you go has always worked best for me, going off an uncommented API is evil when it is complex, i loathe working on some projects because there is absolutly no documentation
the guy who wrote the ldap authentication module for drupal read this because its proving to be a beotch to modify. I know comments suck (speaking as a developer) but god knows their necessary, especially when working on and debugging someone elses code.
/* no */
We come here to get away from work, not to learn how to do it properly. Plus, isn't this a dupe?
/*This loop starts at x is equal to 1 and continues while x is less then 5. x is incremented by 1 each time.*/ for( int x=1; x5; x++ ) { printf("Hello World\n");/*Prints "Hello World"*/ }
# does something important
code
code
code
#not sure what, but it looks important.
... seems to have been turned into sawdust...
That is all.
If it's hard to write, it should be hard to understand... and if it's easy to write, then it obviously doesn't need commenting.
gosh.
My best strategy is intelligent variable names and clean simple code. -- http://www.dreamsyssoft.com
If a non-programmer or somebody with no real knowledge of the project can look at a piece of code and understand what it generally does and how, then you have good comments. But good comments are not always necessary, sometimes subpar will do. Next question.
Looks like some MUMPS programmers should read this article.
I viewed the source on the site and nothing was commented :)
Finance tutorials and more! Understandfinance
Comments are more important than Code?
I once tried writing code that was completely made up of comments. It was easy to write and all, but didn't work very well.
Comments? We don't need no stinkin' comments!
Why would I want to risk my future job security by letting other people know what I am doing?
Seriously, we all need to comment. But, how desperate are we for topics when we have a slashdot submission on "commenting strategies"? All you need to do is get all of the developers in a room and spend ten minutes talking about what should appear in comments. Then, enforce the rules with code reviews.
/* TODO: Flesh out comment here */
Don't comment at all, and just run it thru The Commentator!
http://www.cenqua.com/commentator/
Don't blame me, I voted for Kodos
/*
* FIXME - Should handle slashdotting better.
*/
Karma cannot be described by words alone.
I/* singular pronoun */ try/* verb */ to/* ??? */ comment/* yeah right */ as/* ??? */ little/* really, I do */ as/* ??? */ possible/* probably could have commented per letter if I wanted this comment be funny */
But when reading the article I was glad that the very first item was SELF DESCRIBING CODE. The most important part of code documentation is the code iteself IMHO.
I think it was Fowler who once went as far as to state that when you find yourself needing to document code in order for it to be understood (vs. thoroughness, completness, or document generation) you probably need to refactor your code.
How many times have we come across code like this?
public void bigFunction1()...
public void bigFunction2()...
Write the comments first, then add the code. That way you'll get a better grasp on the problem you're solving. If your comments don't explain the problem or someone else can't solve the problem using your comments then you'll probably need to rethink your approach.
And for crying out loud update the comments when you change code!
*grumbles about 10 year old code and 15 year old comments*
The next generation of professional coders will most likely be good commenters as well. I know from experience in my computer science classes, professors will mark programming assignments down significantly if comments are not included, or if they are hard to read. Most of the time they want all functions to be commented to explain what their parameters mean, how the function works, and the format of the output.
I got nothin'
No, that first one should be something like:
This loop starts at 1, and to 5 it counts. It doesn't count to 6, nor it does count to 8. It does not count to 3 or 4, except in passage to 5. When it reaches number 5, the fifth number...
The AACS key is NOT 0xF606EEFD628B1CA427BEA93A9CA9773F
When I was learning Java in college, the instructor would give your failing grade if you don't have comments and the HTML output of the javadoc utility. The C++ instructors, on the other hand, only wanted your name, class and date in the comments. You would think that all programmers would comment their code.
1) Write article 2) Post on your website 3) Submit to slashdot 4) ...
5) PROFIT!!!111!!!
I pretend to know more than I really do by mooching off google and wikipedia.
Dlugar
Computer Go: Writing Software to Play the Ancient Game of Go
The following is an example of useless documentation:
frobWoggleFfloofMoing
public void frobWoggleFfloofMoing(String, String, String)
...
You see, running Doxygen over your header files may produce some output in HTML format, but it doesn't produce what I like to call "documentation." For instance, documentation would explain what is a Woggle, and when should it be Frobbed?
Thank you, and have a nice life.
From the article: "It is a good practice to write comments at the same time (or earlier than) you write your code."
MSDN on Using Comments Effectively
Odd that i would want to disagree with MSDN (cough) but I actually find it better to do a massive comment on a file or set of files a day or two after they've reached a milestone. This forces you to go through and ensure you understand it. It also makes it so that you're commenting from "outside" the programmer's headspace a little bit. As well... it let's you see those sections where one would normally write /* Oh Fuck */.
This sig used to be really funny...
If success is defined as enhancing your job security, then boobytrap your code with misleading comments to make it impossible for anybody else to work on it.
(in emacs, on a .py)
edit -> select all
python -> comment out region
Voila!
I quit!
I would be interested to know if there is some "official" estimate of how much money is wasted as a result of poor commenting practices. It all obviously depends on the size of the code and the number of people who are responsible for maintaing it.
My personal experience is with one person codes. I was recently in a situation where I was trying to study a code that another person had written and left behind. There was approximately 3000 lines of code with approximately 5 lines of comments. Quite painful, and unnecessarily so.
http://jeffkrimmel.com
Comment out all buggy code, all code written by coworkers and all code written under previous boss. Increses your popularity with current boss.
There you are, staring at me again.
I know the value of comments, so I always try to use them except in the smallest of personal utility programs. But I don't comment as I'm writing code. Instead, I write significant chunks of code, then go back and comment each piece of the chunk. In doing so, I have to think, "Okay, what is this code supposed to do?" and in the process, since I hadn't just finished writing the code, I tend to catch more typos and bugs. Seriously, I've saved myself a lot of time debugging by commenting this way.
I don't know why people (in general) don't like to comment code. I comment mostly for me, so a year or two down the line I'll know why I did something (I've found over the years of writing code, I may think I'll remember, but that often does not end up the case). In the end this selfish purpose ends up helping when other people need to maintain my code (other people fucking around with my code? Never).
"Who are in control, they are not in control of anything - they don't even control themselves!" - Glen Beck
I (sadly) have a lot of experience working with old, ugly code. And I can tell you, I would give up every single comment if I could have a good Architecture. Good architecture adds more value to a code base than does good comments.
code comments you.
For those writing in assembly (and why waste time writing in any less efficent language?), I find the best rule is that every single line must have a comment. Additional comments can be added as needed. I can actually go back and understand my assembly code this way.
I'm an American. I love this country and the freedoms that we used to have.
And don't put in how much of a asshole your boss is and the other coworkers are, unless you want them to see it.
Don't appologize for your code, then promise to fix it later. I saw that done at one company, 3 years after the commenter have left.
Fight Spammers!
1. Never spelchezk. /* magic occurs */
2. Use randomly chosen variable names, or objects that resemble your favorite Orcs and Trolls from LotR - after all, everyone knows that a Lothlorien object will have farseeing ability, so it's obvious.
3. When instantiating something for the first time, never explain it - real programmers read the original object source.
4. If you do something complex, write a short pithy comment like
5. If you do something easy but you were drinking too much hot cocoa, write a long verbose description, and also mention how good the hot cocoa was.
6. Always include song lyrics to what you're listening to while you wrote the code.
7. Object inheritence means never having to explain the code.
8. Repetition is the best way to reinforce obvious things - so repeat the obvious thing since it's the best way to reinforce it.
9. If you break up with your girl/boyfriend, write about it in the comments - people really want to know.
10. If you're updating or modifying code, write your opinion about the original code in the comments. Use nasty words if you can.
-- Tigger warning: This post may contain tiggers! --
# The main function starts here
or...
# This is a loop and it will run while a certain
# condition exists.
or...
# Don't forget to remove this section after
# I'm gone - Dan - 04/25/1995
Think about the children! ;P
-"...bad old ideas look confusingly fresh when they are packaged as technology" - Jaron Lanier (Digital Maoism on Edge.o
i++; // Incremement i by 1 // check if i less than 3 // print "hello world" to screen // if (i 3)
if (i 3){
println("hello, world");
}
The Right Reverend K. Reid Wightman,
It's been said before, but I find the best advice I've ever gotten on commenting code is very simple -
Comment the why, not the how.
Hopefully the code should be clear enough to pick out the how, but *why* you are doing something is never going to be apparent from the code itself - at best someone might be able to infer it, but that becomes especially tricky when time passes or a new person signs on.
Why would I want to risk my future job security by letting other people know what I am doing?
How reasonable a fear is this?
Though commenting improves efficiency by allowing other members of the staff to collaborate effectively, it may also make one irrelavent or very easy to replace if new people can so easily introduce themselves to the methods of doing the work.
(+6, Funny)
and give him some Underrated, not just karma-less Funny.
Of course it runs NetBSD. BTC: 1NT7QvbetmANwaMzhpVL6
I have always written all my comments out before I start to code, it gives me a good idea of exactly what I have to do, helps me to not forget parts of a program, and makes it much quicker overall.
Just make sure that your comments are easily understood by someone in India.. so when they take your job it will make the transition easier.. that way you don't have to train the person that's going to take your job from you..
There is some training involved in any job, but in every job I've had, from fast food to clerical, people disregard at least some of the methods -- particularly with regard to documentation -- so that they can get the job done and stand around or go home.
Today's Excuse: Well I would have commented my code just like they said to, but the site was Slashdotted so I couldn't learn how to do it right. By the time the page finally loaded it was time to deliver the project. But I really, really, REALLY promise I will comment my code next time. Yes, really!
"It's the height of ridiculousness to say for those 9 lines you get hundreds of millions."
*/ Begin pay raise */
Good comments should explain these areas:
a) What you're doing.
b) Why you're doing it.
c) How you're doing it.
I took three assembly programming classes in College. The last one was on the 68k, where we wrote an embedded OS.
Assembly code isn't all that intuitive, and writing comments is especially important. Our professor allocated 20% of our grade on each lab to comments. In addition to accurately describing what we were doing, he checked our grammar. One thing he always stressed is that too many engineers these days don't know how to write comments. Grammar is important in getting the message across unambiguously.
In general, if a person can read your comment and then figure out how to translate what you said into code, then your comment is pretty good. It should give an idea of what you're trying to do, why you're doing it, and how you're doing it.
One of my professor's grad students translated a program from MACRO32 into C++, and all without even knowing MACRO32. He looked through the comments to figure out what they were doing. They were so specific that he could easily translate blocks of code over to C++.
Comments are very important - and I should definitely comment MY code. I can't remember the number of times I've come back to code that I've written and thought "WTF am I doing here? WTF was I smoking when I wrote this?!"
Vivin Suresh Paliath
http://vivin.net
I like
Of course, job security should be your #1 concern. Good comments are just the icing on the cake. After you have implemented deceptive function names (deleteFile -> openFile), hostile macro's (// -> sleep();), just add comments that confirm what the function appears to do on first glance. Add some edge cases as tested and working that will certainly fail, and give some ludicrous versions for the compiler the code has been `tested` with.
Your code is good enough when it seems easier to just feed it to an obfuscator than to use the actual code.
You can find the article text here on MirrorDot.
Tech, life, family, faith: Give me a visit
http://www.literateprogramming.com/
Overall, this fella's article is just stupid. He gives very good examples of bad comments, and then goes on to give some "good" examples, which are just as poor:
var teamCount;
which is it? the count of the number of teams you have, or a loop counter? if it is a loop counter, why not just label it i? Overall this article was useless at best, and down right wrong at worst.
/* You are not expected to understand this */
No folly is more costly than the folly of intolerant idealism. - Winston Churchill
A TRUE Klingon Warrior does not comment his code!
Le français vous intéresse?
One of the other programmers put in a really awesome comment the other day. I wish to share it with you all.
//pd.getInt("numInputs");
My code: (from a core library that services many different code bases)
numInputs = pd.getInt("numInputs");
His comment/fix:
numInputs = 3;
Why parse the parameter database when you already know the answer? Who cares about the other code bases? I WANT THREE NOW!
www.olin.edu
/* comments can be terribly misleading. Debug only the code. */
- Sh!t
All functions/methods (besides accessors) are commented. If a chunk of code needs a comment, it should be refactored into its own method and that method should be commented.
Someone suggested this simple strategy to me a few years ago and I'm surprised at how well others pick up my code quickly. It really does make a big difference.
Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
Anyway, this is the strategy I've come up with after having to go over my old code.
Computers are useless. They can only give you answers.
-- Pablo Picasso
I maintain some legacy code that has, during it's (30 year) life, been converted through various versions of the language making it virtualy unreadable in places. There's one fairly frequently used section commented with:
'not quite sure what this bit does'
It's been like that for years, but whatever it does, it seems to work.
Ask someone else to look at your code. Every time they pause while scrolling, touch their chin, squint their eyes, furrow their brows, etc., it means you need a comment.
[o]_O
This is what I do; I've always thought comments should allow one to reproduce the functionality of the code just by reading the comments. Also makes it much easier to understand what you've done when you or someone gets back to it later.
AC comments get piped to
C++ means never having to.
-- Tigger warning: This post may contain tiggers! --
you're welcome
Get thee glass eyes, and, like a scurvy politician, seem to see things thou dost not.--King Lear
I strongly agree with some of this, especially giving everything clear names, which he calls code commenting. (I hate Hungarian notation, though.) I love TODO comments: they are a great for an author to record thinking about future improvements. And if I'm publishing an API, in-code documentation like JavaDoc are a great way to keep your API docs.
But he doesn't mention unit tests at all, which I think are one of the best places to define what code is for. Unlike regular comments, unit tests can be verified by the computer, so they're much less likely to be misleading or out of date. If you have good unit tests (and especially if you do test-first development), I think a lot of traditional comments become less useful.
This makes me wonder, we all have such rather different strategies for commenting code, why not put it in a blog, like how liz taylor feels about this or that, maybe that's the type of comments we need!
Successful Strategies for Crashing Your Website
This post expresses my opinion, not that of my employer. And yes, IAAL.
It isn't exactly a dupe -- but hasn't this been covered already, sometime in the decades we've been writing code?
Or did we really wait 30-40 years to bother to write up something on how to comment?
What comes first, finding a teacher or becoming a student?
I would imagine that the type of work environment has a lot to do with the amount and quality of commenting as well. For example, I don't work in a commercial production environment; I do R and D in a government agency, which means fairly soft deadlines. I have a lot of respect for people that pump out apps that actually work, and am fairly forgiving of bugs in commercial software for this reason.
"Who are in control, they are not in control of anything - they don't even control themselves!" - Glen Beck
If you comment your code too well, you become replacable.
If you comment your version, and strip them out (maybe strip every other comment?) you become more of an asset since you will be the only guy that knows how your code works.
Sad to resort to these tactics, but it's also sad that your boss will fire you in a whim if he can replace you with a $10/hour new grad.
-judging another only defines yourself
We used to have a template (taken from some government standard or other) for a hugh block of comments to be dumpped on the front of each new program we did for government contracts.
Picky, stupid items, but actually usefull 20 years later when someone else had to take it up.
The syntax for commenting things in the Doxygen style is a little weird, but once you're used to it, its great. I find it much easier to keep my comments up to date than my external documentation, so this way I can do both. In addition, I'm a consultant, which means I often have to look at massive amounts of code written by other people, most of which is uncommented. I find that running any code I have through Doxygen before anything else gives me a nice, clear, high level view of how the code is structured.
Two words: Literate Programming
(S(SKK)(SKK))(S(SKK)(SKK))
Iteration and loop counting is nice, but leads to reader fatigue and antipathy...
;-)
To ensure readability, make sure to translate all iterator use and loop constructs to recursive function calls and definitions.
Besides, if the next programmer can't deal with it, he's unworthy
Since I can't post on his site, here are a few interesting ones:
// Continue original attack if still alive
I'll throw in some disagreement about a couple of things. Code commenting has one purpose: to communicate to a developer at some time in the future how some code works, so that he can adapt/fix it. There is also interface documentation (ie javadoc) but I consider that an essentially solved and separate issue.
Hungarian notation is bad because it discourages descriptive naming. By forcing you to add extra characters to a name indicating type, you decrease the likelyhood that you'll use a long descriptive name, and you don't add any information: type information is already available in the variable declaration. Worse, if you do change types, and don't change the variable signature, then you're potentially introducing misleading information.
Likewise, end of function tags are bad because they can be misleading, and they don't add information that is not available from brace structure (and in any reasonable modern editor, you can easily reformat all text to correct brace indentation).
Similarly, excessive inline commenting can lead to readability problems: if you have too many comments, how do you tell when the author is trying to communicate something important? For example I consider:
if(isAlive) {
isAlive = attacker.attack(defender);
}
A bad comment. It's essentially documenting the usage of the if conditional. The if conditional is self explicit. If there is something interesting about the logic of doing this, perhaps it ought to be code explicit instead:
if(isAlive) {
isAlive = attacker.continueAttack(defender);
}
Also, for your header comments, you'd be very smart to adopt javadoc compatibility, even for c/c++ code. There are lots of tools that make that a smart move.
"Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
From a senior OS student in his shell programming assignment: /*Drunk. Fix later.*/
I read a great quote once, probably in someone's slashdot sig:
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. - John F. Woods
Don't comment.
Write intention-revealing code. Use meaningful identifiers. Write with the maintenance programmer in mind. Code is write-once, read-many. In the days of low-level programming languages and maximum identifier length, comments were at least necessary to explain WTF a PLGRNX1 means. With modern development tools, you don't even have to type out the whole identifier after the first time, you can use code completion.
Too many comments makes me wonder why the programmer couldn't write clearer code.
This is *exactly* how I've approached many problems in the past couple of years, and it has amazed me how many logical errors are visible when someone does a quick peer review of my comment-only pseudo-code. At this point, you don't have to be knowledgeable about the language your co-worker is using. You simply need to have a reasonable grasp of the logical flow to spot potential problems.
Tim
Later on. . .
*scratche head* Hmm....why doesn't my Important Information show up?
Make America grate again!
If you want to write perfectly unmaintainable code, you should follow these guidlines
They explain how to write perfectly unmaintainable code. Suggestions range from naming variable (re-using variables outside of scopes, using single lettre names, using people name), camouflage (using #defines, etc), and many other perfectly normal (albeit evil) strategies
I wouldn't mind you in my head, if you weren't so clearly mad -Lews Therin Telamon
It's as much about what you leave out...
The biggest mistake people make is to use comments to try to explain unreadable code. It fails because the comments invariably fall behind the code and after a while become worse than useless.
My advice:
1. Comment all variables
2. Be 100% consistent with variable names so that the same data always has the same name
3. If your code is too complex to understand without comments, rewrite it and keep rewriting it until it's clear
4. Comment the unusual, do not comment the obvious
5. Style, clarity, and consistency in your code are worth much more than comments.
In summary: if you write code so that it looks *perfect*, very often it will be perfect and comments will be superfluous.
Writing perfect code is hard work. I do it. Few on my team can, but it's always worthwhile.
Ironically, we also rewrite most of our code many times. The biggest benefit from consistency and clarity comes not from getting working programs but from getting code you can lift and reuse with trivial effort.
My blog
None.
if(!comments)
{
return brokenlamp + testicals;
}
Ascalante: Your bride is over 3,000 years old.
Kull: She told me she was 19!
This kind of reviews are really destructive for my goal of winning the obfuscated code contest (http://www.ioccc.org/ can not read any further.
My wife's sketchblog Blob[p]: Gastrono-me
/* If you're reading this comment, that means I
am dead. Go to the Wells Fargo bank on
Huffman street in Peoria, Illinois and open
my safety deposit box
...
find the decryption key to decipher the rest
of the comments in the code. They will
provide further clues
...
stage of enlightenment, you will understand
the purpose of this code. I think you'll
find the algorithm interesting. */
I had a coworker whose comments were so obscure, you had to read the code to understand what he meant.
org.slashdot.post.SignatureNotFoundException: ewg
In this way, you get a nicely documented design that's written right where the developers need it (in the code), you enforce your (presumably good) design with the team as a whole by laying out all the important objects and functions ahead of time, you remain at a high level in comments (since no code is written yet) that is more likely to include information about how functions are used and interact, and you don't force the developer into the position where they have to explain what you, the designer, were thinking.
When you get down to coding, you block out the code in pseudocode comments before you start to coding. I usually like a comment every 10-12 lines of code.
The only pain in the ass is keeping comments up to date as the design evolves, but until there is such a thing as a true Visual IDE (think UML compiler) not much to be done about it except to hound people to do it.
The meek shall inherit the earth, in 3 by 6 plots. - Lazerus Long
Perl is beautiful, the problem is reading perl written by someone without a style of his own...
When a logical person with a clearly defined (perl)style of his own writes perl, the code itself becomes to greatest comments you could ever want.
It might take a while to get used to his style (esp. if the code is more "advanced" than you're used to, and there's a lot of it); but once you're used to his style it's a lot easier to just read the code, than to have to read comments and figure out how they related to the actual code.
perl -e'print$_{$_} for sort%_=`lynx -dump svanstrom.com/t`'
I agree completely with your statement. I only comment because I've learned that 6mo down the line, I won't immediately remember all of the details, particularly if it involved some subtle interactions or assumptions. So I comment because I am humble enough to realize that I'll forget, plus lazy enough not to want to do that work over.
...
However, until you reach that realization, most folks are arrogant enough to think that they will remember all of the details and lazy enough not to want to do the work now
REM MOST /. Readers
REM would write comments
REM like this
' and maybe some very advanced ones
' would use this
Best Buy can have you arrested
torrent?
Write smaller methods. Give those methods clear names. Give clear names to identifiers. Do not repeat the type in the identifier name if it doesn't help identify the purpose of the identifier.
All of these steps lead to code much clearer than similar comments, in my experience.
Three rules of thumb that work fairly well:
1. Use comments liberally to explain why. Why would I want to call this method? Why did you choose this particular algorithm? Why are you ignoring this exception? Source code has very little support for explaining why without comments - and why is often both the most important point and the most easily forgotten.
2. Use comments occasionally to explain what. Your method names, parameter names, and logic should strive to be clear enough that explaining what is happening is unnecessary. But that is in a perfect world. If you can't make it clear in a reasonable amount of time, add a comment explaining what is happening.
3. Never use comments to explain how. The real how diverges from the comment too quickly. If someone needs to see how, they should look at the source code, which is the only reliable resource for explaining how.
There are exceptions to all of these I'm sure, and this doesn't cover everything (for example, the above says nothing parameter definition comments or copyright comments), but they're decent rules of thumb for most cases.
Stop-Prism.org: Opt Out of Surveillance
I'm as guilty as the next folk of not commenting my code. However, I've found that the new Folding ability that vim has really helps me to get into the habit. I tell the editor to fold all {..} blocks, then I can comment arbitrary blocks of code.
Here's a block:
And here it is, commented:
In vim, that folds up into this:
I prefer a design spec before any code is written. And code without comments. and revisions to the design spec to reflect any *minor* changes that happened during implementation.
If you're really lazy putting a short comment infront of every function describing what it does and what it returns is fine. But if you have to describe what the function does maybe you need a less complicated function that can easily be described in its own identifier.
Comments can rarely be trusted anyways. Often code is updated, and nobody bothers to update the comments because they don't care or they aren't even sure what the comments mean. At least with a design spec you have a way to track the design and implementation indepedently. A design spec is always out of date, but at least you know how out of date it is. (please put revisions and dates in your design spec, if your source control doesn't do it for you).
“Common sense is not so common.” — Voltaire
- /* Slashdotted? */
+ echo "Slashdotted!";
We do not have parameters, we have ARGUMENTS. And we ALWAYS WIN THEM!!!
I comment because it is 50% of my grade.
A software engineer with enough experience learns that objects and functions should have a clear, singular purpose. The names of these functions and objects should convey this singular purpose. You can see why each of us has at some time probably wrestled with the concept of "self documenting code". We've all seen code like this and thought "Thank you, commenter. You must love to type."
I've found that once you have the skill to organize your thoughts enough that functions and object definitions don't ramble on forever, the documentation for each function becomes less important. I would assert that even without looking at the body of the above function, the function's name and scope does a very acceptable job of documenting what's going on.
With many small objects and many small functions (which is what I see many "good engineers" doing), the heart of your code's behavior lies more in how your objects interact. I've gotten more in the habit of creating macro-documentation just as much as micro. Instead of repeating myself with every line and function, I describe an overview for each tiny system. If you're looking at my object definition, you will see it prefaced with a comment block to the effect of this:
This object does ____. It may be used for purposes such as ____. It was not designed for _____ because _____. This object relies on these objects _____ for _____. For background on this solution/design pattern/general algorithm, see h t t p : //___________.
It's nice to be able to revistit some year-old system and have a single paragraph in a predictable location refreshing me on exactly what the hell is going on.
I admit I'm not a very experienced coder, but something I find helpful is to write exactly what I want to happen in the program in plain english. Then I go through it all and translate the english into code. You can easily save all the natural language and turn them into useful comments.
:set expandtab :retab
:set expandtab=8 or :set tabwidth=8 or whatever, but I think that should do it.
You might need to do
-gptelemann
You still need to know how to write good comments but I find using doxygen is a great tool for generating useful documentation directly from comments in your code. If you haven't heard of it give it a shot.
http://www.stack.nl/~dimitri/doxygen/ Doxygen homepage.
The Daily WTF is an excellent site that catalogs how NOT to write code and comments.
If it was hard to write the code, it should be hard to understand the code! It's only fair, dammit. : )
I assert that my comment is only my opinion, not that of any employer, past, present or future.
Come on, somebody had to say it...!
They say the mind is the first thing to
If you have to log, and really you should for anything even remotely enterprise or product level, then you have to do a lot of log statments (beyond the braindead stuff that AOP'ers do)
good debug and trace logging statements are about as frequent as comments should be anyway, and the outputted message is usually approximate to the comment message anyway.
unless you're doing resource-managed trace logging, in which case, you crazy man.
Hey, I'm just your average shit and piss factory.
...don't write things like...
/* I have no idea what this portion does and I wrote it, but my daughter says it is good so I guess I'll leave it in but I hope my boss never has to read this in court on the stand in a lawsuit */
Bad idea.
If my grammar and spelling are off, I am [distracted/tired/careless] (take your pick)
12. Specifications are for the weak and timid!
11. This machine is a piece of GAGH! I need dual Pentium processors if I am to do battle with this code!
10. You cannot really appreciate Dilbert unless you've read it in the original Klingon.
9. Indentation?! -- I will show you how to indent when I indent your skull!
8. What is this talk of 'release'? Klingons do not make software 'releases'. Our software 'escapes' leaving a bloody trail of designers and quality assurance people in its wake.
7. Klingon function calls do not have 'parameters' -- they have 'arguments' -- and they ALWAYS WIN THEM.
6. Debugging? Klingons do not debug. Our software does not coddle the weak.
5. I have challenged the entire quality assurance team to a Bat-Leth contest. They will not concern us again.
4. A TRUE Klingon Warrior does not comment his code!
3. By filing this SPR you have challenged the honor of my family. Prepare to die!
2. You question the worthiness of my code? I should kill you where you stand!
1. Our users will know fear and cower before our software. Ship it! Ship it, and let them flee like the dogs they are!
You can go back and forth about which is more important - the code or the comments - but why not harness the capacities of modern programming languages to achieve both? Expressive programming. Well-planned naming conventions and code organization can speak volumes more (and quicker) than the mini whitepapers that often preface blocks of unintuitive code. If the variable 'i' is the current index in the collection, why not just call it 'collectionIndex' afterall?
Sometimes even copious comments aren't helpful. I've seen too much code that looked like this: // include system header(s) // main program // number of arguements in argv array-of-strings //array of string arguements //do magic, James said to put it here. He quit last month. Don't laugh, it breaks if you take it out. //end
#include
main(
int argc,
char **argv
)
{
magic(argc,argv)
}
Knowledge is how to play a game, intelligence is how to win, wisdom is knowing what game to play.
The best basic strategy for commenting code is to flip the script: code your comments. Start writing the program by writing, in English (or your other human language in which you design programs), what the program will do. I start the file with a comment stating what the program will do, with any input and/or output to expect. Then I start writing complete sentences, punctuated, of the steps of processing. Wnen the action is obvious (already described in a comment), I sometimes label code with just a noun clarifying what its operating on. When I've got the comments written, I add code to each section, telling the computer how to do what I said it would in the comment.
/^(.+)\s+(.+)\s+(.+)$/);
:). While this clarity is useful when collaborating with other people, it's useful to consider that you are different when time passes. So reading your own code later is easier. Even if it's Perl, and you're cramming lots of "elegance" into some data structures and regexps - the comments can be clear.
This discipline is tied to my code layout style. I put braces ('{' and '}') each on their own line, in languages which use them to delimit blocks of code (most of the languages I use). After the opening brace, I put a single space, then a comment, like:
# Use list if it has items.
if($numEntries = $#list)
{ # Get personal info from people in the list.
Then I indent the block with 4 spaces, starting with a comment, like:
# Use local storage.
my(@names, @addresses, @jobTitles, $name, $address, $jobTitle);
Loops get described as a single operation, but their block describes each iteration's operation:
# Get columns into separate lists.
foreach $row (@list)
{ # Add fields to their columns.
# Get fields from row.
($name, $address, $jobTitle) =
($row =~
# Store fields in their columns.
push(@names, $name);
push(@addresses, $address);
push(@jobTitles, $jobTitle);
} # each row
} # Used list of people.
The comments, layout and variable names make it easy to understand what's happening. So easy that it's useful to read them first, then write the code
--
make install -not war
From the article:
"Code Commenting - This refers to writing descriptive variable names that are self explanatory."
I once had to work with the derivative a complex equation that was basically on long complicated polynomial divided by another polynomial, so I did the following:
hi = [Long numerator polynomial]
ho = [long denominator polynomial]
dhi = [derivitave of numerator]
dho = [derivative of denominator]
dhiho = [ho*dhi - hi*dho]/[ho*ho]
## corny, but I'll remember it
A goal is a dream with a deadline
Ask someone else to look at your code. Every time they pause while scrolling, touch their chin, squint their eyes, furrow their brows, etc., it means you need a comment.
Furrow their brows to express the anger they are feeling? They just need a baby-T and a visor.
I got this from a co-worker last week...
Unmaintainable Code article gave tips from the masters on how you write code that is so difficult to maintain, that the people who come after you will take years to make even the simplest changes. Further, if you follow all these rules religiously, you will even guarantee yourself a lifetime of employment, since no one but you has a hope in hell of maintaining the code. Then again, if you followed all these rules religiously, even you wouldn't be able to maintain the code!
Ant(Dude) @ Quality Foraged Links (AQFL.net) & The Ant Farm (antfarm.ma.cx / antfarm.home.dhs.org).
Good comments should explain these areas:
a) What you're doing.
b) Why you're doing it.
c) How you're doing it.
In any reasonable program, a should be pretty obvious what you are trying to do. If you include descriptive variables and comment names as comments, I can see that. But a dedicated comment? Sorry. If it gets out of sync with your code, you are !@#$ed. I will admit that sometimes I use comments to give some structure to my code and make sure that I am placing stuff in areas where they can be easily read.
As for why you are doing it. This is the best reason for comments, IMO. Comments that tell you something about why, or what else needs to be done greatly increase the maintainability of the code because they provide a window into what the programmer was thinking when the code was written.
As for how you are doing it? Certainly not. If you must use comments here, then I think your effort is better spent on code readibility in general.
When I have to debug other people's code, I start off by ignoring the comments. When I start to ask myself "WTF?" then I look at comments to see if they provide a reasonable explenation. I also read comments before I make changes. But not when I am tracking down bugs.
I find many programmers provide too many of the wrong types of comments, trying to tell me how their program works rather than telling me why they decided to do one thing or another.
LedgerSMB: Open source Accounting/ERP
// TODO: Comment code.
"My God, this must be a truly remarkable corn chip, to be so widely and confidently touted."
OK, it s not always possible and/or desirable. If it is not broken don't fix it. When I see comment in code because the developer don't understand what happening in 8 level deep statement or in the little function of 10000 lines of code, please fix the code.
there is basic rules to follow; not all exposed here it would be tooooo easy and me way too lazy :) :
Comments are there to
NB: I know javadoc, junit and metrics is for java but...
"Use cases are fairy tales..." I. S. 2005
One company I worked for had a way of dealing with people like you...the rule was:
if a programmer has become indispensible, fire him!
that company, I might add, is still in business, unlike some of the biggest [remember DEC?] I have worked for. Funny thing, now that I think of it. I remember trying to read device driver code for RSX-11 that had hardly any comments in it....my point being most of you will be saying "RSX what? whats he talking about?" Uncommented code dies young. and does nothing for the longevity of the company that tollerated its creation.
SLASHDOT: news for people who can't concentrate on work or have no life at all and got tired of yelling back at the TV.
"Code Commenting - This refers to writing descriptive variable names that are self explanatory. This is a minimalist form of commenting, and looks like this:
function addUserToDatabase(userName, userAge)
Without any additional information, you can tell that the function will add a user's name and age to a database. A common implementation of this is called Hungarian Notation."
Hungarian my ass.
This is Hungarian:
lpszname
What he describes is simply good variable naming.
hard core geek-ware
I'm working with a mass of code (php, perl) that has no comments at all. Like, none. And generic variable names ($counter, @array). My first task as I try to determine what the code does is to run through it and add comments.
//comments from quickie #!comments. //Notes about how the program does its thing
/* big notes; headers, etc. */
//? Todo - Places I need to come back to and figure something out
//! Error - Places where something is wrong
/*
I tend to use many types of comments. This way I can find and see the #!errors or #?todos - and at least in PHP I can tell long-term
#dates mod'd, etc.
#? or I'd like to rewrite for speed, etc.
#! or an error occurs/might occur
# (commented-out code)
Commented out code
(big blocks of commented-out code)
*/
It's fairly frustrating that comment syntax differs btw perl and php since I go back and forth a lot.
After all, Linux 2.6 is mostly obfuscated OpenServer (well, the multiprocessing parts at least).
I once came across this particular "gem" in a system I was tasked with taking on from a defunct software house: /* TODO: Fix to work after 1999 */
The system in question was a financial brokerage tool which, needless to say, had plenty of chunks of code that subtracted and added arbitrary numbers to 2-digit years before reconstituting it again. What made it worse was that instead of using established library functions (it was written in Perl), or even custom written functions, these mistakes were repeated and duplicated hundreds of times throughout the codebase.
To be fair the author had the foresight (laziness?) to comment all of the sections which weren't Y2K compliant with "TODO" comments, which made it marginally easier to fix.
would this be a good time for someone to explain to me why CSS doesn't support // comments, only /* ?
This comment does not represent the views or opinions of the user.
For instance:
Simple, clear, no need for comments.
"Hardly used" will not fetch you a better price for your brain.
I sure wish the guy who originally wrote the program I'm currently debugging knew what a comment was. He constantly did random weird stuff and never commented any of it. That's real fun -- I now have lots of comments in the code like:
// I have no idea what the point of this is, but it seems to be screwing up {whatever}.
// I'm going to try to comment this block out to see if it fixes the problem.
;-)
Not to mention the amount of time I have to spend to implement what ought to be trivial changes to this project. ARGH!
"Commenting your code is like cleaning your bathroom"
Since when does my girlfriend comment my code?
"If you are a dreamer, a wisher, a liar, A hope-er, a pray-er, a magic bean buyer
commented code should look like it was a technical paper or article. The problem is IDEs and code editors don't support this very well. You really want some sort of view control that lets you keep the comments out of the way. Or some way of annotating the code without cluttering it up, ie. keep the comments out of line unless you want to see them. Hyperlinks maybe. A source file is just a data structure but we haven't progressed very far since punch cards.
I recently took a contract somewhere as an 'engineer' where I was probably the only one who had an engineering degree. Also the work I was doing was far from engineering (web programing). Also I've been on interviews where the client sets me up to talk with their "engineer" who probably doesn't even have a college degree. The problem I've run into is that many times the ones doing the hiring have no idea what they are talking about. To them the engineer is the guy who can use the terminal, or can write HTML by hand.
Another problem ( I think I'm on a rant here ) is that some people say they want an engineer when what they want is a designer, they want someone to make their site look pretty, and they really don't care about functionality. They just figure "Its too technical for me so I must need an engineer."
(The situation isn't helped by people who use flash and call them selves an engineer)
Unless the economic value of comments in code is quantified, one should take care not to comment it. I don't know of any study demonstrating this value. Any pointer?
IIRC it was in Enlightenment, around v15 or so
/* Drunk, fix later */
"They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety" - BF
I can understand where people are coming from that they fume about having code without comments dumped on their laps. On the other hand, how do they know they will understand the code with the comments? Or even understand their own comments a year from now?
I am more in the lean-comment rely-on-descriptive-variable-and-function-name camp, and if there is commenting, it should concentrate on interfaces or on broad architectural outlines. If I find myself commenting on how I did a hack, I ask if I can rewrite the code in a non-hacky way.
By the way, for all you Delphi programmers out there, is the VCL source code from Borland commented? Not really. It may have banner copyright notices but it is pretty comment spares. And when there is a comment, it is usually a pretty gross hack they are rationalizing.
See below.
"God fights on the side with the best artillery." - Napoleon, Marshal of France - speaking truth to power
first use something like ruby , where commments are turned straight into documentation
also if your code is using useful variable names and function calls everything should be self explanitory
less spagetti, more cowboy
back in the day we didnt have no old school
In my experience, I've found that a lot of people write functions that are too damn long. Sometimes this is because a shoddy programmer got into a cut-n-paste session when he should have used abstraction, or someone just gets in a hurry and tries to do too much at once.
I, as a rule, try to limit any one function to a page of code; if if starts to get longer than that, I start looking to see if I can break things down into smaller steps. The benefit of this approach is that functions are small enough to be easily unit tested and the code is short enough that you can't get too confused about what it's doing. Add a header comment describing what the function does, what the inputs are and any gotchas (eg. this function bombs on null input values) and you're golden.
'No Comment'
MSBPodcast.com The opinions expressed here are my own. If you don't like 'em... Think up your own stuff.
He's testing and indexing on "teamCount" but incrementing "i". Am I missing something? Is there something about JavaScript that will make this loop terminate someday?
PHEM - party like it's 1997-2003!
// For everything else, there's Master Card
Okay, I don't really "code" but I do write scripts. They too should be commented. I prefer to put the date and my initials in the comment as well as what changes or additions that I have made. I usually comment at the top of the script then make a place marker by the section that was modified.
But, I must admit that the ultimate comment is the name of the file/script itself.
If it is a script that the boss made me write, then I'm screwed so I name it the obvious like "scriptbossmademewritethatdoesthisandthat". But, on the other hand, if it's a script that I wrote to make my life easier (and this is important) do not name it something obvious that will draw attention to itself, cause questions to be raised, etc. Name it something that will make sense to yourself and not your enim...err... boss.
For example instead of name naming it "findpayrollfile" name it "whereiswaldo"? BTW I actually did this.
"A government is a body of people, usually notably ungoverned." - Shepard Book Quoting Malcolm Reynolds
I predict, without reading other post, that there will be one or more posts here claiming that comments are bad. Furthermore, I predict that at least one of these posts will be modded up.
How can I predict this? Easy! We always get them everytime the subject of code commenting has come up on Slashdot. Some will be touting the moral superiority of literate programming, others will be giving anecdotes about excessive comments as an excuse not to comment, and still others will claim that comments are bad because no one ever updates them when they update the code.
Now let me go read the comments and see if my prediction was correct...
Don't blame me, I didn't vote for either of them!
How to Write Unmaintainable Code. Enough said. Read it.
One reason why the 'code should be commented' versus 'code should be self-documenting' debate refuses to die is that different programmers are exposed to wildly different programming environments. I don't mean languages and IDEs, though that's a factor, but rather things like a) amount of time maintaining code as opposed to writing it, b) amount of time maintaining /other/ people's code rather than own, c) variety of styles seen in other people's code versus everything conforming to strict guidelines, d) variety of application types maintained and most importantly e) raw complexity and counterintuitiveness of the application domain.
No, you don't usually need much in the way of code comments for your cookie-cutter timesheet app, PHP forum or IRC client. A page or two of overall design documentation probably covers the essentials. But if you're designing a 3D engine, an optimised IP stack or a virtual memory manager then you're probably going to have some serious magic that merits explanation. In my field (experimental artificial intelligence) it's usually extremely hard to understand what other coders are doing even in principle, and detailed comments are damn near essential.
Nobody has ever asked me about it - I wonder if anybody has ever seen it?
I found it useful to comment segments of my assembly code with its C (or your favourite more readable language) counterparts, since it's easier to read.
This way, I'd have a column in assembly, and a column of C code doing the same thing (commented out), so I can figure out what's going on.
- shazow
doesn't even come close to being complete without some discipline. (Sort of like B&D/S&M for your code. :-)
:-)
I've found that while you can come up with 'accurate'
class 'noun' names, and sometimes meaningful
- class,
- classInstance and
- instance variable 'moun' names, and sometimes meaningful
- class and
- instance method 'verb' names, and once in while an insightful
- method parameter 'adjective' names,
they are NEVER placed in an explicit context.
That gives me 'cerebral hives' when the darn thing blows up because something happens that you weren't expecting.
I write my comments in a class method called 'comment' where I describe all of the other classes that this class is expecting to collaborate with.
Then for each variable, I describe what classes it can be expected to hold as a value.
Then for each method, I describe the inputs, if any, (and what classes they can be expected to hold) outputs, if any, (and what classes they can be expected to hold) and a description of the algorithm implemented (not the algorithm itself).
Whenever, in a method, I have an internal loop of any size (like 2 lines sometimes), I break if into a separate 'loop method' (subject to the same 'verb' naming constraints of the method of origin.)
I use accessor methods (all variables are provided with a 'get' and a 'set' method which really don't need *much* documetation
Sometimes, I create 'aggregator' classes for the parameters in and out in the package or parcel.
Then before I release the code, I go back and make sure that the changes are reflected in the class comment.
MSBPodcast.com The opinions expressed here are my own. If you don't like 'em... Think up your own stuff.
If you're going to comment out an entire block of code, do it as: /* //*/
//* //*/
foo
bar
now if you want to uncomment the whole block, you simply add another whack to the top comment
foo
bar
foo bar is no longer commented out. this comes in very handy when commenting/uncommenting entire blocks of code.
-- Binary Finary
Comments are like sex. When they're good, they're great. When they're bad, they're better than nothing.
Comments shouldn't tell you what the code does, they should tell you what you wanted the code to do. That way, if there's a bug and what the comment says the code should do disagrees with what the code is actually doing, then you know you've likely come to the right place!
Ben Hocking
Need a professional organizer?
I like the idea of putting completely random nonsense words, often things taken from games, in strange places, just to make people wonder what the hell I was thinking when I wrote it, even though I write otherwise intelligible code.
I find it extremely useful to document the data structure returned from some funky API call - particularly useful for date/time constructs and other things where what is returned is not at all intuitive and/or riddled with exceptions:
# The datetime() subroutine in date.pm returns the following array items:
#
# 0 = year in blecherous two digit format: 05 = 2005 or 1905 (need conversion utility for that!)
# 1 = month in the following format: 0=January, 1=February, 2=March, etc...
# 2 = day of the month. Note: days 10 have no leading zero!
# 3 = day of the week in the following format: 0=Sunday, 1=Monday, etc...
# 4 = hour. Note: hours 10 have no leading zero!
# 5 = minute. Note: minutes 10 have no leading zero!
# 6 = second. Note: seconds 10 *DO* have leading zero!
import date;
@mydate=datetime;
Later, when I have to extract the data out of the array - or more importantly have to troubleshoot why the output date/time information is off, I can easily interpret the results (e.g. why is $mydate[0] a 4 digit number? Did someone change the library module?).
# Note: Non-functional example code for illustrative purposes only...
Lodragan Draoidh
The more you explain it, the more I don't understand it. - Mark Twain
Threadeds theory of coding states that a High Level Language is only for communicating what you intended for the computer to do to another programmer.
What the computer actually does although superficially adhering to what the programmer intended does at numerous points diverge.
threadeds blog
I glanced through the essay and while there are some good suggestions the suggestions are inadequate.
/* Install window frame */ just before the hammer strokes? Well - this is why the analogy between a technical writer's world and a carpenter's world is weak at best even though it is overused.
Lets look at the function call for instance.
1) the data type of the parameters is not given and the method how these parameters are passed is not given.
2) we do not know if data is sent into the function via certain parameters or if the function returns data via certain parameters. We have no idea of the valid range of values and what units the parameters are expressed in. With (1) above - we have no idea how to call the function.
For instance suppose the function is to check the depth of something. We might expect the depth to be passed in as float, but what precision? Is the depth in inches, cm's, meters, feet, KM's? Nasa lost multi-million dollar probes because of this.
3) there should be a description of the function and any limitations, exceptions etc. in its operation.
4) preferably there should be some outline of the algorithm used so we know if the function has a chance of performing satisfactorally.
5) there should be date created and last revision information and a note why and by whom.
6) we should be able to extract the function documentation in a printed form - preferably with a decompiled call sequence and a list of all functions our function may call - system generated - and suitable for a manual with PAGE FORMATING inserted as requited by the utility that does the extract.
In this way if an up-to-date manual is required of our library then we can generate it simply and completely and instantly from one source: the code. Look at Doxygen for ideas in this area.
----------------
Consider what would happen if a carpenter documented a house. Would it be appropriate to write notes like:
However - the construction of a house is usually documented and its called the blue prints. Most carpenters do not dive into the construction of a house without a blueprint (although some can do a masterful job even if this step is skipped). Unfortunately most programmers are too optimistic.
The best program documentation is done BEFORE the program is written and takes the form of the skeleton I described about. With this skeleton in the form of comments in the sources - the library manual(s) can be printed off and reviewed and it becomes apparent to all what the library is going to do and how it is going to do it. Weaknesses can be easily corrected often before any significant amount of code has been committed.
Also with the code in the sources we are left with the situation that inconsistancies can be corrected easily.
BTW - I have written the vast majority of my code in this fashion for the last 20 years and it has saved my bacon many times. Also being in the position to tell management that a fully up-to-date manual can be printed off at any time with an hour's notice seems to instill a lot of confidence.
I was a grader last semester for an upper-division operating systems course that I'd taken a couple semesters earlier. Here's my implementation of a certain function:
/* if am holding the lock to this thread */
/* returns true if the lock is being held */
/* false if not */
int lock_do_i_hold(struct lock *lock)
{
return curthread == lock->holder;
}
Here's how it was implemented in one of the assignments I was grading:
int
lock_do_i_hold(struct lock *lock)
{
if (lock->curthread == curthread)
{
return 1;
}
else
{
return 0;
}
}
It took great strength of will to keep my grading comments civil.
Better to light a candle than to curse the darkness.
Fix a bug and then fix the comments..
Lots of Comments are a big hassle.. I am willing to say around 20% Maximum of your code should be extra comments.. the rest better be in the code.
Maintaining comments is just as bad as code.
I can program myself out of a Hello World Contest!!
Code should be a mix of self commenting, and comments where a non-obvious work around was applied.
/**
n sAndReturnsTheRightValue obviously might need some reworking if it is too complex, an can be broken up neatly.
Here is the answer to your question:
public int getAge() {
return age;
}
public int getNumberOfDaysUntilNextBirthday() {
return nextBirthday - today;
}
You see, self documenting, now a bad example: (IMHO)
* Dispose method that calls a cleanup method.
* This method is called when the object is
* disposed
* @author Suck
*/
public void dispose() {
cleanup();
}
You see, bad because: the comment is bigger than the method, the person who wrote the comment didn't even write the method, but put an attribution for writing this comment... the existence of a comment would draw undue attention as a seasoned programmer would think it must be a special case to warrant such an epic description. The method itself is a simple built in method overridden to possibly cleanup some resources in a nice error friendly way (in case of borking). The comment literally describes the code, not the function (syntax not semantics). The person who wrote it was an arrogant twat.
I could go on, but an example where code is necessary is when you want to clarify the possible return conditions (if a method is null safe etc)
if you do have a largish method, write the meat of it in a line, so you know how to use it. If you have a 10 parameter graphics method that draws a boofork on the screen, desribe those parameters, dont write:
@param String[] args The arguments
tsk. Code should be written neatly so it is self commenting like:
if (condition)
loads of lines of code
else
loads of lines of code
becomes
if(condition)
callMethodA();
else
callMethodB();
Now a maintainer would see, ok, if X then this or that, and can skip over now, as the NAME of the method becomes a nice double edged weapon - it comments the code, and removes the complexity from the method, and now you have two simpler methods with nice names that say what they do.
A method that should be called checksTwoConditionsAndThenDoesTheAppropriateActio
It helps - software engineering is more like writting a novel than building an engine.
To confirm you're not a script,
please type the word in this image: groups
#hostfile 0.0.0.0 primidi.com 0.0.0.0 www.primidi.com 0.0.0.0 radio.weblogs.com
Yes all the other well meaning advice is good, some of it essential to good code/comments. But it always pays to put some humor into your code, be it funny variable names (that don't sacrifice clarity!) or entertaining commentary. With proper variable assignment, I've written lines that said open("the_pod_bay_doors", HAL) else print ImSorryDaveICantDoThat;
My favorite opportunity is when you want to say something to the user and have them hit the any key so you can continue. The input statement needs a variable, the enduser will never see it's name, and you'll never need to reference it anywhere. Perfect for one liners laid like a bomb waiting for some co-worker to find. "Ira_eats_pork", "Diane_wears_army_boots", and "Kamal_loves_the_Backstreet_Boys" have all brought great exclamations from other cubicles where I've been working.
On the one hand you take life too seriously, and on the other, you do not take playful existence seriously enough. Seth
In the late 60's a friend came up with a comment that has lived with me since (on an assembler code electronics equipment simulator) " Don't touch the r-register" We worked hard to fit the stuff in the available 8k or so words (18 bits?) in those days.
The example at the end that show how he thinks you should do things are broken. While it is useful to give your variables meaningful names, it is less useful if you give the same variable different names.
For that matter, I think that, if something is a simple loop counter, it should has a one letter name like 'i', so that someone reading the code can tell at a glance whether you're doing anything unexpected. Also, it's confusing to reuse a variable for a different purpose, and dead assignments are also bad. (isAlive has the liveness of different participants at different times, and ends up with the attacker's liveness if the defender's teammates attacked or if the attacker was killed before attacking, and the defender's liveness otherwise. Also it depends on the variable being initialized silently to true; otherwise, attackers don't attack unless defenders did a preemptive strike that didn't kill them.)
If I have to comment on what my code is doing, in the majority of cases there is a problem with how my code is written. Comments for why something is done in code is a lot more useful when the why is not obvious. That and API documentation (publically explosed method headers, for example) are where I see comments being uself. The article takes commenting to an extreme, and ignores the real problems which create the desire to comment heavily. From TFA:
// Boolean inidicating life or death after attack // Loop counter // Check for pre-emptive strike // Continue original attack if still alive // See if any of the defenders teammates wish to counter attack // TODO: Process the logic that handles attacker or defender deaths
// End beginBattle
function beginBattle(attacker, defender) {
var isAlive;
var teamCount;
if(defender.agility > attacker.agility) {
isAlive = defender.attack(attacker);
}
if(isAlive) {
isAlive = attacker.attack(defender);
}
for(teamCount = 0; teamCount < defender.team.length; i++) {
var teammate = defender.team[teamCount];
if(teammate.counterAttack = 1) {
isAlive = teammate.attack(attacker);
}
}
return true;
}
All of these comments get in the way of reading the code. However they're required because this method is not written well. The variable names are not self describing. The method also violates the Single Responsibility Principle on multiple counts. The method is also too long (mainly due to the SRP violations). Instead of spending the time mudding up the code with comments, spend the time refactoring the code so that the majority of the comments aren't necessary in the first place. Comments main purpose is to assist a developer in understanding the code. If too much of this assitance is necessary, it is probably due to problems with the code itself; even problems which may have a negative impact on the codebase beyond readability issues.
There is no longer anything that can be done with computers that is nontrivial and clearly legal. -- Paul Phillips
Agreed 110%, even from code I wrote only a year or two ago, I too agree on your statement:
:)
" I can't remember the number of times I've come back to code that I've written and thought 'WTF am I doing here? WTF was I smoking when I wrote this?!'" - by vivin (671928) on Monday August 01, @01:10PM
You've been there, done it, & from one coder to another? I can tell... been there myself!
My compliments to you, and well said reply!
*
APK
P.S.=> I appreciate especially your comments about Asm NOT being "that intuitive" because compared to HLL's (like BASIC, PASCAL, etc., especially RAD & OOP modern 4th gen stuff) it's FAR from it, & also how you stated that even 'bastardizing' the code (assuming via #defines & Macros), good commentary can get ANYONE (especially later generation maintenance coders) thru it... or @ least help!
I don't know about you guys, but I contract out a LOT, and have to maintain the code of others. This takes grasping what they were up to, and without comments? Well, it takes more than that it should... commentary, SOLID commentary? Helps large! Right in the code... apk
While it was nice to see self-commenting code as the first item, WHAT'S THIS???
* Return: Boolean indicating life or death
*/
function calculateHitPoints(cUser) {
If this function tells me whether the user survives the hit or not, name this function isHitFatal, or something like this.
Yes, I'm nitpicking. Because this is supposed to be an exemple of a good comment. And while the comment is good, the function name is not.</rant>
I have discovered a truly remarkable proof for my post which this sig is too small to contain.
Anybody who uses it is a terrorist. (Or a pEvilbeardTrrist, as they like to call themselves)
...is to put in comments that obfuscate, rather than clarify. I mean, the only people making use of your comments will be: You (ok fine), and the ones that replace you (screwem!). /* pwnage! */
Comments are designed to mitigate brain drain, at least in theory. All management wants comments, but no management is willing to extend a deadline to allow coders to comment. This is a lot like ISO 9660 -- in theory, the procedure manuals match praxis, but in practice, the trolley left for La La Land when the night shift cleaned up the empty plastic champagne cups, and won't be seen again until certificate gets revoked. On the other hand, the guy most likely to appreciate the distance between documentation and disaster is you -- but only checking yourself into Four Years Ago will ever help you understand your own notes.
``Tension, apprehension & dissension have begun!'' - Duffy Wyg&, in Alfred Bester's _The Demolished Man_
Anybody ever seen the comment header at the beginning of screenhack.h of Xscreensaver fame? Any comment that includes that many appropriate references to Monty Python deserves some kind of award!
In Soviet Russia, code comments you! In Korea, only old people comment code (I, for one, welcome our new code-commenting overlords)
I am Spartacus
" find the best advice I've ever gotten on commenting code is very simple - Comment the why, not the how."
Another one I like is:
"Comments on data are usually much more helpful than on algorithms." -- Rob Pike
I can't count the number of times where I've been reading through some code which has comments like "transform foo for the analysis loop" and "write foo to the instrument buffer" while all the while I'm wondering, "What the hell is 'foo' and where the hell did it come from?"
dragonhawk@iname.microsoft.com
I do not like Microsoft. Remove them from my email address.
We've got a program at work that, once in a great while, aborts with the message, "Call Bob".
Bob hasn't worked there in years.
*sigh*
dragonhawk@iname.microsoft.com
I do not like Microsoft. Remove them from my email address.
This sig is false.
// how not to do it
// planned to fix something here, but now can't remember
So far I've just been using comments as reminders to myself. Sometimes I don't use any comments at all, and have almost entirely single letter variable names, and the thing works on the first compile. If I do use a lot of comments, it'll be to create a skeleton of something before I fill in the code.
Also point 10a. Threaten the original coder in comments.
I once told the author of an offending piece of code that if I ever found out who (s)he was I would break all ten of their fingers so they could'nt code again. A page down I told him I would also be breaking his toes so he could not code with his feet.
John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
Sometimes I think that was the most usefull line I wrote in that whole job. Then I think some more and I'm sure of it.
John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
When I do analysis I add comments to code as I understand what parts do. If I have spent the time to figure it out, even if I do not need to change the code then my time is valuable and it is worth leaving breadcrumbs for the world to follow later.
This is the best article on comments I have seen. Not a perscription just a collection of techniques.
Leaving your code spread in tiny pieces all over the project and bogging your CPU in call overhead.
The right size for a function? As big as it needs to be. Splitting a single function at an arbitrary point is misguided. Split along functional lines. Sometimes it IS that complicated.
That said it usually is'nt that complicated and a page or two is a good place to start to look for a place to split on functional lines. But if everything is interdependant leaving the solution in one place to be understood can be a better solution then hiding parts of the solution from the coder.
Complexity hiding is good. Complexity obfuscation is bad. Reconciling these two points is part of what makes design an art.
John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
The point is you don't understand it. How much time should you spend refactoring working but shitty code? (Knowing that this type of code has usually evolved to the point it is at. No one actually created a public called aLocalArray, someone changed the scope. That is not a joke, I've seen it. See my comments on threats of bodily harm in code.)
In practice the best you can do is add comments with questions when you don't understand. Hopefully someone who does will add a comment, at least you will be reminded to continue thinking about WTF is going on.
John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
I believe we can learn a great deal on how to write good comments by studying the kernel coding style at http://lxr.linux.no/source/
Slashdot = Sarcasm
Best I saw was in a sorting algorithm. It had some nested loops going on, and two of the variables named as such:
...and...
// Count variables.
bela
lugosi
Puzzled, I dug a little deeper and found the curious explanation:
Boom boom, the children of the night, what music they make...
John
$rv = "0 but true";
if ($rv) {
print "yup\n";
}
if ($rv == 0) {
print "uh-huh\n";
}
That's right kiddies, lose weight, code better, and feel better. Commenting does it all, it's the new miracle cure. All you have to do is spend hours a day adding useless comments to your code like "The function addUser adds a user" and your standard of living will increase ten-fold. While you're at it, why don't you try our miracle weight loss pill; lose 50 pounds in a week and it automatically comments your code for you.
Seriously though, comments do have their place, but when every line of code is dwarfed by ten lines of comments, it's hard to follow the code. Also, people need to stop taking up entire lines with - and stuff like that. Between that and slashdot, I think I've sprained my mousewheel.