Beta
×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Successful Strategies for Commenting Your Code

Hemos posted more than 9 years ago | from the good-things-to-learn dept.

Programming 500

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."

cancel ×

500 comments

Sorry! There are no comments related to the filter you selected.

Huh? (5, Funny)

tntguy (516721) | more than 9 years ago | (#13214973)

These comments you speak of, they seem foreign and strange to me.

Re:Huh? (3, Funny)

bluelip (123578) | more than 9 years ago | (#13215045)

"The code was hard to write. The code should be hard to read."

Was that some form of early DMCA or IP lockdown?

Re:Huh? (2, Funny)

TommydCat (791543) | more than 9 years ago | (#13215065)

/* Please phrase your reply in the form of a comment. */ /* Thank you */

indeed (0)

Anonymous Coward | more than 9 years ago | (#13214978)

indeed, that's the problem

-- marc

Re:indeed (2, Interesting)

CowboyBob500 (580695) | more than 9 years ago | (#13215153)

I agree (I think) with you.

Comments should be common sense and used where the developer thinks it is appropriate and where they will aid future developers/maintainers understand a particular block of code. Nothing more, nothing less. The article is just typical PHB management bullshit and I feel dumber after reading it.

The scenario that is the ultimate end product to "comment standardisation" is what happened at a company that a friend of mine works for. They had a developer sit there for 3 days, go through the entire code base, and format the comments to the "company standard". No shit.

Bob

My favorite code comment not written by me (4, Funny)

dcarey (321183) | more than 9 years ago | (#13214983)

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 */

Re:My favorite code comment not written by me (0)

Anonymous Coward | more than 9 years ago | (#13215138)

At my job, I had to go in and do some maintenance on some old code.

Right at the top was this comment..

/* My appologies to the poor SOB who has to work on this! */

Re:My favorite code comment not written by me (4, Funny)

lukewarmfusion (726141) | more than 9 years ago | (#13215152)

So you found that, eh? *evil chuckle*

I was in a similar spot a month or two ago and found some other company's comments - unhelpful as always - in the form of typed out sound effects.

# This function goes vroooooooommm-pop!

I have no idea why the developers put such comments there other than to entertain themselves as they sifted through their horribly written Perl.

What makes a good Comment? (4, Interesting)

vivin (671928) | more than 9 years ago | (#13215195)

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?!"

Don't do it! (0, Funny)

Anonymous Coward | more than 9 years ago | (#13214985)

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!

Re:Don't do it! (1)

BaudKarma (868193) | more than 9 years ago | (#13215179)

Indispensible, and pretty much unpromotable.

Me, I hope to be able to pass this project on to some junior dweeb in a year or so, and move on to something New and Exciting.

Re:Don't do it! (2, Insightful)

treerex (743007) | more than 9 years ago | (#13215219)

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.

Great idea! The myth of indispensibility is a great reason. May your next job be as a maintenance programmer in a Perl shop where the previous "indispensible" developer had his ass fired for threatening the boss and you get 50,000 lines of Perl dumped in your lap.

it was hard to write (1)

hsmith (818216) | more than 9 years ago | (#13214986)

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

Re:it was hard to write (1)

Rei (128717) | more than 9 years ago | (#13215165)

it should be hard to read!

Like this piece of code?

for(teamCount = 0; teamCount < defender.team.length; i++) {

It's not the comments that are making this code confusing - it's the fact that 'i' is not defined in the function, and thus must be a global. Having a global named 'i'? Now that's bad code!

Methinks that perhaps they meant to write:

for(teamCount = 0; teamCount < defender.team.length; teamCount++) {

I wish (0)

Anonymous Coward | more than 9 years ago | (#13214992)

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.

Gotta say it (2, Funny)

modi123 (750470) | more than 9 years ago | (#13214993)

/* no */

Re:Gotta say it (0)

Anonymous Coward | more than 9 years ago | (#13215036)

No again.  That should be

/* no
   no
   no
   What part of no didn't you understand */

and

// no

Re:Gotta say it (1)

modi123 (750470) | more than 9 years ago | (#13215204)

Or my email sig /* Halley */ Halley's Comment *smirk*

Next article... (0)

Anonymous Coward | more than 9 years ago | (#13214995)

We come here to get away from work, not to learn how to do it properly. Plus, isn't this a dupe?

Example (3, Funny)

dduardo (592868) | more than 9 years ago | (#13215000)

/*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"*/ }

No (5, Funny)

rbarreira (836272) | more than 9 years ago | (#13215054)

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...

Mod parent way up :) (1)

TCM (130219) | more than 9 years ago | (#13215147)

(+6, Funny)

and give him some Underrated, not just karma-less Funny.

Re:Mod parent way up :) (0, Offtopic)

rbarreira (836272) | more than 9 years ago | (#13215164)

Never mind about the karma, I think I have enough already. Thanks anyway ;)

Re:No (1)

Conspiracy_Of_Doves (236787) | more than 9 years ago | (#13215197)

9 is right out

Re:Example (1)

Metasquares (555685) | more than 9 years ago | (#13215056)

That's actually an example of something TFA says explicitly not to do - it's the "Don't insult people's intelligence" tip.

All in all, I found that the article's guidelines matched pretty closely to my own commenting style. I second the author's recommendations.

and don't (1)

www.sorehands.com (142825) | more than 9 years ago | (#13215111)

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.

Re:Example (1)

sykjoke (899173) | more than 9 years ago | (#13215145)

Jesus, you write comments like my old employer wanted me to!!, he didn't like comments like.... /* display hello world 5 times*/
for( int x=1; x5; x++ ) {
        printf("Hello World\n");
}

Re:Example (1)

JustOK (667959) | more than 9 years ago | (#13215228)

But, where does the function end??? And what's this LOOP you talk of? Also, although we don't know what you're doing here, the company standard is to use i.

comments (1)

jchawk (127686) | more than 9 years ago | (#13215001)

# does something important
code

code

code

#not sure what, but it looks important.

The ParticleTree... (1)

frank_adrian314159 (469671) | more than 9 years ago | (#13215002)

... seems to have been turned into sawdust...

Been said many times before... (0)

Anonymous Coward | more than 9 years ago | (#13215003)

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.

var names (4, Insightful)

rockytriton (896444) | more than 9 years ago | (#13215004)

My best strategy is intelligent variable names and clean simple code. -- http://www.dreamsyssoft.com [dreamsyssoft.com]

human readable (1)

cerelib (903469) | more than 9 years ago | (#13215008)

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.

Re:human readable (1)

superyanthrax (835242) | more than 9 years ago | (#13215085)

I disagree, good comments are always necessary. Working in a CS research group has allowed me to see how important commenting code actually is. We may think we're all tough and we can read any program from scratch, give yourself a 2000 line program you've never seen before and you'll change your tune. It will take you far too much time and effort to read that program and figure out what it's doing if there are no comments clearly telling you. One of the most important purposes of writing code is so it can be reused, and if you don't write good comments it will be very hard to reuse.

Re:human readable (1)

jersey_emt (846314) | more than 9 years ago | (#13215161)

I agree, but a 2,000 line program is a *very tiny* one that would (in most cases) be easy to parse through as long as it has good form (proper indenting, meaningful variable names, etc.).

Re:human readable (1)

Conspiracy_Of_Doves (236787) | more than 9 years ago | (#13215095)

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.

Then good comments are... what? Undesirable?

Re:human readable (1)

naarok (102579) | more than 9 years ago | (#13215112)

I'll agree (mostly) with the what, but not the how.

A non-programmer should be able to determine the what, but the what should come as much from the naming choices as from the comments.

If your comments are explaining how the language works to the point that a non-programmer can understand it. You've gone too far with your comments. Long before this point, the actual code that programmers will need to maintain will have become obscured by the comments and you will have made the code harder to maintain.

In general, the primary purposes of comments is for maintenance (either by someone else in a months time, or by you in a years time).

Re:human readable (1)

cerelib (903469) | more than 9 years ago | (#13215232)

the difference of the what and how is needed. In the case of C style languages, the what would be the general comments for a function that explains what the function is supposed to accomplish. The how is more of the internal function comments explaining the process that is being used to accomplish the task.

Re:human readable (0)

Anonymous Coward | more than 9 years ago | (#13215137)

..and before you know it, they've hired a cheaper programmer.

Terse comments. (0)

Anonymous Coward | more than 9 years ago | (#13215010)

Looks like some MUMPS [slashdot.org] programmers should read this article.

Practice what you preach (5, Funny)

ChrisF79 (829953) | more than 9 years ago | (#13215013)

I viewed the source on the site and nothing was commented :)

Comments are more important than Code? (4, Funny)

jetkust (596906) | more than 9 years ago | (#13215017)

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.

Re:Comments are more important than Code? (4, Funny)

NialScorva (213763) | more than 9 years ago | (#13215149)

At least you had no compile errors or core dumps, and I bet you didn't have any exploitable vulnerabilities either.

Re:Comments are more important than Code? (1)

VanWEric (700062) | more than 9 years ago | (#13215190)

But it compiled and ran REALLY REALLY fast!

comments? (1)

lucabrasi999 (585141) | more than 9 years ago | (#13215021)

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.

Office Space -- how realistic? (1)

rwade (131726) | more than 9 years ago | (#13215144)

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.

TODO (1)

mccalli (323026) | more than 9 years ago | (#13215025)

/* TODO: Flesh out comment here */

Re:TODO (1)

networkBoy (774728) | more than 9 years ago | (#13215058)

//Lovely.

Don't comment (5, Funny)

i.r.id10t (595143) | more than 9 years ago | (#13215035)

Don't comment at all, and just run it thru The Commentator!

http://www.cenqua.com/commentator/ [cenqua.com]

Successful strategy (1)

koh (124962) | more than 9 years ago | (#13215038)

/*
* FIXME - Should handle slashdotting better.
*/

How much do I comment? (0)

Anonymous Coward | more than 9 years ago | (#13215039)

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 */

Re:How much do I comment? (1)

Reverend528 (585549) | more than 9 years ago | (#13215126)

You can't comment a statement in its own language unless you intend to comment the comments as well. And that always ends in recursion:

I /* singular /* adjective /* noun /* noun /* noun /* noun /* noun /* noun ....

I was skeptical at first regarding the topic (5, Insightful)

Anonymous Coward | more than 9 years ago | (#13215044)

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()...

Commenting (4, Insightful)

Hamster Of Death (413544) | more than 9 years ago | (#13215046)

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*

really being stressed in schools (3, Informative)

StarvingSE (875139) | more than 9 years ago | (#13215048)

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.

Re:really being stressed in schools (1)

Conspiracy_Of_Doves (236787) | more than 9 years ago | (#13215163)

My old C++ prof would mark down for too many comments or unneccessary comments.

People Cut Corners Once in the Workforce (1)

rwade (131726) | more than 9 years ago | (#13215174)

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.

Re:really being stressed in schools (1)

djmurdoch (306849) | more than 9 years ago | (#13215194)

Comments were stressed just as much when I was taking programming courses ~30 years ago. The problem isn't that people aren't taught to write comments. There are lots of reasons that people don't write good comments:

  - It's hard, and it's hard to know that you got it right: Getting code right means the program works. Getting the comments right and there might be a payoff months in the future.

  - Lots of programmers aren't good writers. Comments are written for people to read.

Re:really being stressed in schools (2, Informative)

j-tull (201124) | more than 9 years ago | (#13215216)

As one who has graded many undergraduate programming assignments I can tell you that professors very seldom actually read, let alone provide feedback on, comments. Comments on assignments tend to be scored as, "Are they there? If yes, good! If not, -10 pts for being a dumb ass."

Summary: Though the next generation of coders may be more diligent about including comments (at least initially -- though I'm not sure I'm even convinced on this point), there is nothing that leads me to believe the content and appropriateness of their comments will be any better than what we see today.

Re:really being stressed in schools (1)

shic (309152) | more than 9 years ago | (#13215229)

I disagree that schools emphasising the value of comments will make students better at commenting. An analogy would be that the value of literature is already emphasised by schools - yet still relatively few students become great authors.

What's So Hard About Comments... (2, Interesting)

creimer (824291) | more than 9 years ago | (#13215059)

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.

Re:What's So Hard About Comments... (1)

pete6677 (681676) | more than 9 years ago | (#13215148)

I strongly agree that students should be taught from the beginning to comment their code. That being said, when I was in school I noticed that the instructors who were the most anal about comments were the least effective at teching programming. One teacher in particular (not really a professor) would fail an assignment entirely if the comments were not exactly like she wanted them, and the requirements were quite complex. However she didn't have a clue about programming beyond the examples listed in the textbook. Needless to say the only things I learned in that class were what I had taught myself.

Successful Strategies for crashing your server (1)

Toba82 (871257) | more than 9 years ago | (#13215060)

1) Write article 2) Post on your website 3) Submit to slashdot 4) ... 5) PROFIT!!!111!!!

Don't tab inline comments! (1)

Dlugar (124619) | more than 9 years ago | (#13215063)

Properly tab comments Make sure comments are tabbed out to the line they are referencing. Additionally, make sure similar comment types align when tabbed.
Both those who prefer indenting with tabs and those who prefer indenting with spaces tend to agree: use spaces for alignment. Otherwise when somebody with a different tabstop comes along, your comments will be all out of whack.

Dlugar

Re:Don't tab inline comments! (1)

I8TheWorm (645702) | more than 9 years ago | (#13215141)

True that. I use UltraEdit for most of my coding now, and it has a nice tool built in for converting tabs to spaces and vice versa.

There's nothing worse than loading up a project someone else wrote and had their tabstop set at one space. I think they do that on purpose :)

Re:Don't tab inline comments! (1)

Metasquares (555685) | more than 9 years ago | (#13215188)

I find the expand utility (which probably comes with most Linux distros) very useful for this. Type tabs in whatever IDE you're using, run expand when you're done, and you have spaces. I imagine that most editors even go so far as to build this feature in, though I've never bothered looking it up in vi.

A comment on comments (5, Insightful)

Jeffrey Baker (6191) | more than 9 years ago | (#13215064)

Dear Doxygen and JavaDoc users,

The following is an example of useless documentation:

frobWoggleFfloofMoing

public void frobWoggleFfloofMoing(String, String, String)

Frobs the Woggle

...

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.

Re:A comment on comments (1)

Abcd1234 (188840) | more than 9 years ago | (#13215207)

ROFL. That reminds me of the documentation for the Scientific Atlanta PowerTV APIs (these are the APIs used on various digital settop boxes). They have exactly that style of documentation, *printed*... it's *immensely* frustrating.

When to comment... (1)

EWIPlayer (881908) | more than 9 years ago | (#13215066)

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 */.

Depends how you measure success (1)

Linus Torvaalds (876626) | more than 9 years ago | (#13215070)

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.

The best strategy (1)

2008 (900939) | more than 9 years ago | (#13215071)

(in emacs, on a .py)

edit -> select all
python -> comment out region

Voila!

How much money is wasted in bad comments? (1)

madscientist003 (857924) | more than 9 years ago | (#13215074)

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.

Best strategy for comments, so far... (1)

Maljin Jolt (746064) | more than 9 years ago | (#13215075)

Comment out all buggy code, all code written by coworkers and all code written under previous boss. Increses your popularity with current boss.

My commenting habits (2, Interesting)

TildeMan (472701) | more than 9 years ago | (#13215080)

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.

Why I comment code... (4, Interesting)

Saeed al-Sahaf (665390) | more than 9 years ago | (#13215081)

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).

Re:Why I comment code... (1)

fishbowl (7759) | more than 9 years ago | (#13215146)

"I don't know why people (in general) don't like to comment code."

I always put a boilerplate header in every source file with a copyright and proprietary notice (required by my company's policy), and I also comment everything that's not and extremely obvious implementation of the design as already documented, and certainly, anywhere the implementation diverges from the design. Also, anything that's incomplete, or not implemented as well as I'd like it to be, gets a "TODO" or "FIXME" comment.

But local variables don't get explained in the comments, and neither do member functions that are already spec'd in the design docs (which they all are.)

To go any further, I'd need to add 10-30% more time on every source file, which is not an option given the production pace in my environment. However, I already know from substantial experience that maintenance folks consider my code to be a pleasure to work with. I'm quite proud of that, and it's not just about "comments" or "style".

Architecture is more important than Comments (1)

olivermoffat (211767) | more than 9 years ago | (#13215086)

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.

IN SOVIET RUSSIA ... (1)

Ihlosi (895663) | more than 9 years ago | (#13215090)

code comments you.

Assembly code (1)

frovingslosh (582462) | more than 9 years ago | (#13215094)

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.

Re:Assembly code (1)

WillAffleckUW (858324) | more than 9 years ago | (#13215212)

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.

Good thing I write in assembler, so I don't need to comment. What is this assembly you speak of?

Things to always remember when commenting (4, Funny)

WillAffleckUW (858324) | more than 9 years ago | (#13215113)

1. Never spelchezk.
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 /* magic occurs */
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.

All Depends... (3, Funny)

eno2001 (527078) | more than 9 years ago | (#13215119)

...on who is going to be reading the code after you are gone. Sadly, due to differing levels of expertise, there is no optimum method of commenting code. For some, this is a very useful comment (I'm using pound sign comment designation as an example):

# 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

Sample Comment (0)

giminy (94188) | more than 9 years ago | (#13215131)

i++; // Incremement i by 1
if (i 3){ // check if i less than 3
      println("hello, world"); // print "hello world" to screen
} // if (i 3)

How & Whys (4, Insightful)

Anonymous Coward | more than 9 years ago | (#13215136)

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.

Ive always... (1)

Neticulous (900423) | more than 9 years ago | (#13215172)

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.

Look out... (0)

Anonymous Coward | more than 9 years ago | (#13215173)

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..

As Always, Just Out Of Reach (1)

Nom du Keyboard (633989) | more than 9 years ago | (#13215191)

Proper commenting, as usual, remains just out of reach.

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!

All the commenting you need (1)

dakkon1024 (691790) | more than 9 years ago | (#13215193)

*/ Begin pay raise */

My strategy (0)

Anonymous Coward | more than 9 years ago | (#13215196)

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.

Mirror (1)

Swamii (594522) | more than 9 years ago | (#13215198)

You can find the article text here [mirrordot.org] on MirrorDot.

Literate Programming (0)

Anonymous Coward | more than 9 years ago | (#13215202)


    http://www.literateprogramming.com/ [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; // loop counter

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.

Important (1)

koreaman (835838) | more than 9 years ago | (#13215223)

A TRUE Klingon Warrior does not comment his code!

My favorite comment (1)

VanWEric (700062) | more than 9 years ago | (#13215225)

One of the other programmers put in a really awesome comment the other day. I wish to share it with you all.

My code: (from a core library that services many different code bases)
numInputs = pd.getInt("numInputs");

His comment/fix:
numInputs = 3; //pd.getInt("numInputs");

Why parse the parameter database when you already know the answer? Who cares about the other code bases? I WANT THREE NOW!

Misleading... (1)

quark007 (765762) | more than 9 years ago | (#13215227)

/* comments can be terribly misleading. Debug only the code. */

My simple strategies (1)

FortKnox (169099) | more than 9 years ago | (#13215233)

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.

My take (2, Interesting)

lawpoop (604919) | more than 9 years ago | (#13215239)

I'm a self-taught PHP hacker. I've fooled around with VB for MS Access and I hate it -- way too crufty with ADO and DAO, but I digress...

Anyway, this is the strategy I've come up with after having to go over my old code.

  • Every 'flow control' statement (if, while, else, etc) gets a comment in plain English about what conditions it's checking for.
  • Every logical block of code gets a 'mission statement' saying what large-scale, abstract task about what they are supposed to accomplish. When I say 'logical block', I'm not talking about something the computer will understand, but an abstract grouping of lines of code meant to accomplish a high-level task.
  • For some obscure functions or arguments, they will get a comment at the end, just to help myself with parts of PHP that I'm not familiar with. This is just to keep me from looking up things, and other PHP hackers may not need this commentary to understand the code and its function.

At Least Be Honest (1)

s7uar7 (746699) | more than 9 years ago | (#13215246)

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.

zerg (5, Insightful)

Lord Omlette (124579) | more than 9 years ago | (#13215249)

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.

Comments should reproduce code (1)

Sebby (238625) | more than 9 years ago | (#13215250)

It is a good practice to write comments at the same time (or earlier than) you write your code.


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.

Load More Comments
Slashdot Login

Need an Account?

Forgot your password?

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>