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!

How to Write Comments

CmdrTaco posted more than 8 years ago | from the no-not-the-slashdot-kind dept.

Programming 556

Denis Krukovsky writes "Should I write comments? What is a good comment? Is it possible to comment a class in 5 minutes? See " Everybody knows that good code is self documenting- which is why my prof in college demanded we write in Ada. I instead suggest commenting in haiku.

cancel ×

556 comments

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

Reading (5, Funny)

Southpaw018 (793465) | more than 8 years ago | (#14147378)

Code should read easy Like many Slashdot comments See? It's not so hard.

Re:Reading (5, Funny)

Southpaw018 (793465) | more than 8 years ago | (#14147403)

*grumble* Forgot the <br>s.

Code should read easy
Like many Slashdot comments
See? It's not so hard.

MOD PARENT UP. (1)

3-State Bit (225583) | more than 8 years ago | (#14147464)

ha, I thought you were making a subtle point!

Re:MOD PARENT UP. (1)

Southpaw018 (793465) | more than 8 years ago | (#14147484)

Oh snap. I should have just kept my mouth shut. O_o

Re:MOD PARENT UP. (1, Interesting)

$RANDOMLUSER (804576) | more than 8 years ago | (#14147526)

> No one at Microsoft has ever had anyone murdered.

Tell that to Gary Kildall [wikipedia.org]

Re:Reading (4, Interesting)

jmony (245233) | more than 8 years ago | (#14147410)

Problem with Slashdot comments is like code comments... too few is bad, too much is bad. // This line outputs the result

How many times can we see a line like this... that's just writing comments without any reason.

I prefer function header comments which describe what the piece of code as whole does. Not everyline, as teachers say it should be done.

Re:Reading (1)

netkid91 (915818) | more than 8 years ago | (#14147496)

if (lart == true);
(
console.write("Go away luser");
);

Re:Reading (1)

$RANDOMLUSER (804576) | more than 8 years ago | (#14147589)

Silly sysadmin! LART is always true!

Comments (5, Funny)

LiquidCoooled (634315) | more than 8 years ago | (#14147385)

<!-- Damn users clicking too quickly on article -->
<!-- why don't they ever RTFA? -->
<b>Nothing for you to see here. Please move along.</b>

Re:Comments (0)

Anonymous Coward | more than 8 years ago | (#14147440)

REM Mod parent up.
REM Yeah, I know this is in BASIC, so bite me

Re:Comments (5, Funny)

Golias (176380) | more than 8 years ago | (#14147652)

/*
This is my comment. There are many like it, but this one is mine.

My comment is my best friend. It is my life. I must master it as I must master my life.

My comment, without me, is useless. Without my comment, I am useless. I must author my comment true. I must write clearer than my code which is trying to obfuscate my efforts. I must comment in before it gets me fired. I WILL...

My comment and myself know that what counts in this job is not the lines we write, the size of our file, nor the time to compile it. We know that it is the completed change requests that count. WE WILL COMPLETE...

My comment is human, even as I, because it is my life. Thus, I will learn it as a brother. I will learn its weaknesses, its strength, its words, its letters, its punctuation and its opening & closing tags. I will ever guard it against the ravages of re-edits and cruft as I will ever guard my legs, my arms, my eyes and my heart against damage. I will keep my comment clean and ready. We will become part of each other. WE WILL...

Before God, I swear this creed. My comment and myself are the defenders of my department. We are the masters of our code. WE ARE THE SAVIORS OF MY LIFE.

So be it, until the beta goes gold and there are no further patch requests, but sales!

Back in grade 12 (1, Informative)

Data Link Layer (743774) | more than 8 years ago | (#14147390)

There was a final project worth 50% of our final grade (it took 3 months todo) I didn't comment and I fail it.

Re:Back in grade 12 (0)

Anonymous Coward | more than 8 years ago | (#14147450)

I'll bet you failed English, too.

Re:Back in grade 12 (-1, Redundant)

Anonymous Coward | more than 8 years ago | (#14147651)

me fail english? that's umpossible!

Haiku Commenting? (4, Informative)

drewzhrodague (606182) | more than 8 years ago | (#14147394)

Actually, that would give some of us that have to review code something interesting to look at. Those that think code is self-commenting, forget that there are people like me, who aren't great programmers, who have to either fix your bugs, make simple modifications, or add really simple things. When there aren't comments, it is hard to figure out what parts of what do which.

Re:Haiku Commenting? (4, Insightful)

mcvos (645701) | more than 8 years ago | (#14147489)

When there aren't comments, it is hard to figure out what parts of what do which.

What parts do what should be clear from the names of function calls and variables, but whenever a function becomes longer than something really short, yes, it needs comments describing what happens where. If a function does something complicated, it's worth starting with a comment describing pre- and post conditions.

That said, before you add a comment, first check if you can make the various identifiers any clearer. And then still add the comment, unless it's suddenly become really stupid.

Re:Haiku Commenting? (5, Insightful)

PsychicX (866028) | more than 8 years ago | (#14147534)

Possibly the best advice I ever read/heard (I can't remember the origin), is to assume that the guy reading your code is perfectly familiar with the language. (Sadly this is usually inaccurate, but moving on.) So he can see what, mechanically, your code is doing. The idea of a comment is to explain how and why you are doing something. What is usually clear from the function name and accompanying documentation (be it doxygen/javadoc style or MSDN style or something else). I.e. if you have some jacked up mega-compound for-loop, a good comment explains why that loop is the way it is, and how it's achieving its goal (and possibly what precisely it's doing). A bad comment would be "this loop increments i, j, k, theta, and cheez_it until the cheez_it is failing to exceed the sum of i, j and the product of i, j, and k". That kind of information is right there in the code.

In short, comments convey concepts and explanations, not mechanical descriptions.

Re:Haiku Commenting? (4, Insightful)

Rorschach1 (174480) | more than 8 years ago | (#14147668)

I'd suggest an exception to this for embedded code. When I'm writing something for a PC, sure, there's no excuse for not making the code readable. But when you're squeezing as much functionality as possible into a chip with maybe a couple hundred bytes of RAM and a few KB of flash, things get ugly.

It's not uncommon for my code to do something really non-obvious to accomplish a task in a more efficient way. Processing sensor readings, for example - on a PC it'd be a simple floating point math operation. On the chips I use, the floating point library would itself fill the entire available memory. Instead, I wind up with a bit of hard-to-read code that accomplishes the same thing using the shift and multiply operations the CPU is good at. For my own sanity I leave very specific comments about what's going on and what the equivalent calculation is.

A bad question... (3, Funny)

Snamh Da Ean (916391) | more than 8 years ago | (#14147395)

Asking Slashdot "Should I post comments?" is a bit like asking turkey's "Should we cancel Christmas?".

Let the commencement of the comment posting beginulate!

Re:A bad question... (1)

Snamh Da Ean (916391) | more than 8 years ago | (#14147487)

Before anyone feels the need to point it out, I apologise the the stray apostrophe in turkeys...

cenqua! (5, Funny)

i.r.id10t (595143) | more than 8 years ago | (#14147399)

Simple, and I've posted this link a few times before, but you really need to use cenqua. Takes all the pain out of comments, and still allows personality quirks to show thru.

The Commentator [cenqua.com]

Just be careful on your settings and you should be fine.

Re:cenqua! (0)

tacocat (527354) | more than 8 years ago | (#14147537)

Cute, but worthless. Just fills pages with arbitrarily obvious statements

CODE is a language in itself. So is English (or your preference). The problem is finding a bridge between the two that makes sense. I can't write comments for my PHB, he shouldn't be looking at the code anyways because he's an idiot and it will only make him feel stupid, which causes me a lot of extra work.

So who is the audience?

Here you go... (0, Troll)

casualsax3 (875131) | more than 8 years ago | (#14147409)

Comments in Haiku Worst idea ever Submitter go home

Re:Here you go... (1)

Xaositecte (897197) | more than 8 years ago | (#14147515)

dear casualsax,
you have a stick up your ass.
Kindly remove it

Re:Here you go... (0)

Anonymous Coward | more than 8 years ago | (#14147658)

> dear casualsax,
> you have a stick up your ass.
> Kindly remove it

dear Xaositecte,
you have a grudge on your shoulder.
be nice, and casualsax might let you remove that stick for him...

Ditch the signatures (-1, Offtopic)

Anonymous Coward | more than 8 years ago | (#14147413)

Sigs are useless and annoying. Usually, it's a one-liner obscure geek reference that nobody cares about.

---------------
42 - That's my sign. George. All the way. Hooplah!

Check out Rob Pike's thoughts on code commenting (5, Informative)

podz (887481) | more than 8 years ago | (#14147415)

Rob Pike, a former powergeek at ATT&T labs, and a present powergeek at Google, has the following [lysator.liu.se] to say about code commenting. In general, I agree with him.

Re:Check out Rob Pike's thoughts on code commentin (5, Insightful)

squiggleslash (241428) | more than 8 years ago | (#14147550)

I'm not sure I do.

He's used two stupid examples of commenting, examples that are popular jokes, rarely appearing in real life and usually the result of sarcastic nudge-nudging from experienced programmers, and pretended that's what we're talking about when we talk about commenting. When he finally admits they may have a use, the description is so vague it's hard to see what he means - which, if he comments the same way, is probably as true of his code as it is his prose.

It doesn't take much, or add any clutter to code, to put a brief, one or two line, comment before each paragraph of code, that describes the intended functionality of the code block. It makes a massive difference when you revisit your code three years, or even three months, later, or worse have a collegue look at it.

Nor is it a massive imposition to have more obscure decisions you've made be explained in a comment block before the code itself.

Code is not self-documenting. It becomes intensely verbose when you try to make it self-documenting, and it's rare that anyone, no matter how well skilled, can produce something that transmits the intended functionality of the written code in the implemented functionality. This is especially true if you're using an optimal algorithm. Reasonable, non-excessive, use of comments, describing functionality rather than function, are extremely important.

Re:Check out Rob Pike's thoughts on code commentin (2, Insightful)

prgrmr (568806) | more than 8 years ago | (#14147570)

"Procedure names should reflect what they do; function names should reflect what they return"

This is one of the most effective methods of producing self-commenting code and I wish everyone writing programs would do this.

Re:Check out Rob Pike's thoughts on code commentin (1)

eronysis (928181) | more than 8 years ago | (#14147623)

What a great read! Thank you!

Good code is self documenting... (5, Insightful)

Private Taco (808864) | more than 8 years ago | (#14147419)

Just like good documents are self coding...

Re: Good code is self documenting... (1)

Rob the Bold (788862) | more than 8 years ago | (#14147558)

That is the trick, though. You put too many comments in your code, and you end up maintaining your comments as well. Or worse, you end up with code that obviously doesn't match the comment. Or even worse, you end up with code that doesn't match the comments, but not obviously -- sort of software counter-intelligence.

Re: Good code is self documenting... (1)

Malc (1751) | more than 8 years ago | (#14147567)

With well-commented code and a syntax-directed editor, I find it easier and quicker to read comments than reading the code. If I suspect there is a problem in the code, then I start to read it.

The best way to code + comment is to write out the algorithm or steps of a function using comments, and then fill the code in. Good commenting is a bit of an art, and definitely takes a while to learn more through experience than instruction.

Re: Good code is self documenting... (0)

Anonymous Coward | more than 8 years ago | (#14147635)

Thats utter crap btw. When you need to implement a complex algorithm it doesnt matter
how well its written, how well its formatted, how clean it is, the complex nature of what
its doing needs to be commented. even if its just a small short few lines at the top
describing what the algorithm is for and what its doing, even better if it says how it works.

self commenting is nonesense. good code has good clear and well understood comments in it.

dont over do it, dont comment every line, dont write a novel, keep it clear and concise and dont comment the obvious. (like if checkit == 0) doesnt need a comment normally so dont over do it.

its an art like anything else, but good code is definatly not self documenting.

Re: Good code is self documenting... (4, Interesting)

bunratty (545641) | more than 8 years ago | (#14147673)

Yeah, right. I recently debugged some code that did matrix calculations. It turns out that the matrix involved was always positive definite, and therefore the calculation could be done by performing Cholesky decomposition rather than explicitly taking the inverse of the matrix. Needless to say, there were no comments explaining any of this, and it took me hours to reconstruct the thoughts and derivation behind the original code.

Here's the original code:
L = Cholesky(cov0);
th1 = L.i() * th0;
lrt = (th1.t() * th1).Trace();

which is supposed to compute the same answer as the code:
lrt = (th0.t() * cov0.i() * th0).as_scalar();

I do agree that in general code should be self-documenting when possible, but sometimes you need a few lines of comments to explain a single line of code, or a few paragraphs of comments to explain a few lines of code. I added 17 lines of comments to that part of the program to explain 3 lines of code.

Nothing beats good comments (1)

ccccc (888353) | more than 8 years ago | (#14147421)

I know a lot of people say comments are unnecessary if you have nice self-documenting code. But personally I find nothing beats a short comment at the top of chunks of code to give a quick idea what it's doing (or supposed to do).

Re:Nothing beats good comments (1)

Miros (734652) | more than 8 years ago | (#14147499)

Yeah, I'd have to agree with that. Writting large ammounts of code is easier if you dont have to comment, and if you're a decent programmer your code should be clear enough to get from reading it. But at the same time, if you're trying to debug or add a feature, it really helps to know what parts of a function do what without having to read the code to find out.

Re:Nothing beats good comments (1)

Threni (635302) | more than 8 years ago | (#14147541)

> I know a lot of people say comments are unnecessary if you have nice self-documenting code.

It's a moronic argument. You should (sometimes) explain why you are doing something, not just what/how you are doing it. Yes, you should be following a design brief/spec, but documentation that's not in the source code *will* get lost and is pointless.

Re:Nothing beats good comments (1)

khendron (225184) | more than 8 years ago | (#14147591)

It is only some types of comments that are unnecessary. While it is true that you can figure out *what* is happening just by looking at the code, what you cannot see is *why* something is happening. And it is the *why* that is the most important.

Re:Nothing beats good comments (1)

HunterZ (20035) | more than 8 years ago | (#14147593)

I know a lot of people say comments are unnecessary if you have nice self-documenting code. But personally I find nothing beats a short comment at the top of chunks of code to give a quick idea what it's doing (or supposed to do).

My thoughts exactly. I can't recall how many times I've looked at sparsely-commented code and ran away in terror (or at least scratching my head). In my opinion it's essential to comment your code at some level. Finding that level is the hard part: you have to step back from what you're doing and think about the thought process of someone looking at your code who is unfamiliar with it. This usually means a comment of appropriate length at the beginning of most chunks of code, with a few more specific comments along the way if you feel you're doing something obscure.

I feel fortunate to have a programming job in which a good portion of my code is peer-reviewed (and - perhaps more importantly - in which I also review others' code), as I feel that I've gained some valuable insight into how to better write and comment code.

I find it likely that the majority of those who believe that well-written code is always self-documenting probably haven't worked on a large project in which people bend a code framework around to do all sorts of crazy things, nor have they had to do a significant amount of review of others' code in such an environment.

Comment every conditional branch or loop (4, Funny)

Matt Ownby (158633) | more than 8 years ago | (#14147424)

I once read that a good comment will appear on every conditional branch or loop, and a good comment will also state the INTENTION for doing something, rather than what is actually being done (because the programmer can usually figure out what is being done). For example: // i starts at 1 instead of 0 because we don't want to process the application's name (first argument)
for (int i = 1; i argc; i++)
{
    printf("ARgument is %s\n", argv[i]);
} // AND with 0xFF1234 because that is the first set of bytes in the file header
if (u & 0xFF1234)
{
    printf("File is valid.\n");
} // say file not found instead of invalid due to reason blah blah blah ...
else
{
    printf("File not found.\n");
}

Re:Comment every conditional branch or loop (4, Funny)

KilobyteKnight (91023) | more than 8 years ago | (#14147492)

// say file not found instead of invalid due to reason blah blah blah ...
"blah blah blah" is mostly what I use for comments also :)

Re:Comment every conditional branch or loop (4, Insightful)

MemeRot (80975) | more than 8 years ago | (#14147568)

Comments can be good,
Avoid 'magic numbers' too,
You've heard of constants?

Seriously, this is not good code: if (u & 0xFF1234) - what the hell is u? Is it the start of the file? What if your file structure changes, you want to grep for every instance of 0xFF1234 and see if it needs to be changed? What if you changed your definition of what a good file is?

Why not: if isValid(fileStart) - or if all you're doing is printing, just put it in the print statment? You do have to comment to explain why you're doing something, but the clearer the code is the easier it is to read and maintain.

commenting made easy... (1)

nick-less (307628) | more than 8 years ago | (#14147425)

guide here [thedailywtf.com]

Dupe! (1, Offtopic)

tpgp (48001) | more than 8 years ago | (#14147426)

Covered here [slashdot.org]

Oh... you meant code comments... never mind!

Re:Dupe! (1)

op12 (830015) | more than 8 years ago | (#14147649)

Ada Rocks (1, Insightful)

Anonymous Coward | more than 8 years ago | (#14147427)

It's like C++ with some thought to design...

Re:Ada Rocks (0)

Anonymous Coward | more than 8 years ago | (#14147480)

How do you read a single keystroke in Ada without waiting for the return key to be pressed? Is there a simple function that will do this, like INKEY$ in BASIC?

Denis who? (1, Insightful)

Anonymous Coward | more than 8 years ago | (#14147433)

Who is Denis Krukovsky, and why should I (or anyone) care what he says?

I did RTFA: it was poorly written and makes some statements that most people would STRONGLY disagree with. For instance:
The point to start writing comments is... when the code is ready to be presented for others.

Sure (3, Funny)

Praetorian42 (248627) | more than 8 years ago | (#14147436)

Sure my code is readable, but more often than not I find my comments explaining the screwed up business logic behind the code.

The why not the how (4, Insightful)

Ckwop (707653) | more than 8 years ago | (#14147437)

A comment should tell you why something is in place rather than what the code is doing:

A trival example:

Don't do this:

public bool CheckSmsValue(Account smsAccount)
{

// Check tarriff is null
if (Account.Tarrif == null)
          return;
...
}

Do do this:

public bool CheckSmsValue(Account smsAccount)
{

// 30-11-2005 Fixes a null reference exception that occurs later on if no reference is available.
if (Account.Tarrif == null)
          return;
...
}

Simon.

Re:The why not the how (1)

BarryNorton (778694) | more than 8 years ago | (#14147519)

// 30-11-2005 16:08 GMT Fixes a type checking error when no value is returned
if (Account.Tarrif == null)
                    return false;

Re:The why not the how (1)

Youssef Adnan (669546) | more than 8 years ago | (#14147619)

// 30-11-2005 16:08 GMT - (myemail@myco.com) Fixes a type checking error when no value is returned if (Account.Tarrif == null) return false;

Haiku (0)

Anonymous Coward | more than 8 years ago | (#14147441)

this block for mailing
checks addresses for error
errors on failure

*bow*

Words to live by (5, Funny)

3CRanch (804861) | more than 8 years ago | (#14147447)

During college I always lived by:

"It was hard to write; it should be hard to read"

'course the profs didn't appreciate that much...

No (1)

trollable (928694) | more than 8 years ago | (#14147454)

You should use Java instead (or another easily readable and understandable programming language). Ok there may be some cases where a comment is needed but it is quite rare. Give the source, that should be enough. Of course, if your design is complex, you should write design/technical documentation (but it is out of the scope of comments anyway). Don't hide important information into comments, give it its own status. Don't clutter your code with comments. IMHO.

The classic (1)

$RANDOMLUSER (804576) | more than 8 years ago | (#14147458)

You are not expected to understand this (1)

Rob the Bold (788862) | more than 8 years ago | (#14147520)

I've used some of the corallaries to this comment, e.g.

/*Be afraid. Be very afraid.*/

Once I actually did use the "/* you are not expected . . ." comment and got a severe talkin'-to by my boss about being a "team player". After that incident, I only commented in Latin and Klingon for that employer.

You should not comment on your code (1)

raingrove (934820) | more than 8 years ago | (#14147459)

Try your best to make your code unreadable by anyone else other than you. That will keep you employed :P

Comments tell reason. (4, Insightful)

Daniel_Staal (609844) | more than 8 years ago | (#14147460)

The code can tell me what it is doing, but it can't tell me what it is supposed to be doing. The comment should tell me why the code is doing what it is doing. Then I can look at the comment and code together and tell whether the code is right. (And the comment won't have to change as I modify the code: It either stays because the why still exists, or it is removed because it doesn't.)

You are not expected to understand this (1)

b1t r0t (216468) | more than 8 years ago | (#14147462)

I once managed to put an "All Your Base" reference in a series of comments, and have them actually be meaningful to the code.

Re:You are not expected to understand this (1)

tlhIngan (30335) | more than 8 years ago | (#14147606)

Skillful commentors are able to insert their phrase-du-jour into the code at the right place.

Unfortunately, I'm not a skillful commentor - so I often fail to work in quotes that I have in my head, or thoughts, or characters into my comments. Would be nice since the code can then serve as a journal...

("I can't believe I liked the book then! Sheesh!")

Haiku? (1)

Twitch42 (91037) | more than 8 years ago | (#14147465)

golden urn soiled
grandfather desecrated
by a confused cat

My coding comments are about as useful as my message board ones.

Forget the comments (1)

Lxy (80823) | more than 8 years ago | (#14147477)

Learn to write Submissions [slashdot.org] first.

News? Matters? (1)

BarryNorton (778694) | more than 8 years ago | (#14147493)

// Redundant.comment while(story = slashdot.getStory()) { story.read(); eyes.roll(); }

Three Books to Read (3, Informative)

CortoMaltese (828267) | more than 8 years ago | (#14147494)

Three pretty good books that have insightful views on how to write readable code and comment it appropriately:

In short, they all suggest writing readable code is more important than commenting spaghetti, but there are also good points on commenting. (Can't be bothered to copy-paste them here, though, see for yourself.)

Comments First (4, Insightful)

Doc Ruby (173196) | more than 8 years ago | (#14147500)

Good comments are written first, before the code, describing what the following code does. It is gramatically correct, punctuated, easy for a stranger to read. It says what the following code does in terms of the real world, not just in terms of other code, unless the sole purpose of the code is to connect other code without relation to anything expressible in real world terms. I prefer my comments to be in the present tense, as if they could be directly compiled themselves. I put comments inside practically every block, like function definitions, loops, conditionals. I often put comment labels after block closers, especially complex conditional sets, embedded loops and functions. That labeling makes it easier to keep track of context within which variables, their scope and the "current task" are in operation. I'd rather spend a few more seconds typing up front, and save a lot of scrolling and delimiter-matching later (not to mention reducing confusion and mistakes).

Code gets shuffled around in different order, read by strangers, and reread much later by yourself, often after you've changed by experience (either in programming or in the task being programmed). Writing the code first is a good way to outline the program, and to detect flaws in your approach. It also gets a little bit of the program done, on screen where you can see it. Often coding to support the comments is more like a cleanup task than starting from scratch.

Re: Comments First (4, Insightful)

Black Parrot (19622) | more than 8 years ago | (#14147549)

> Good comments are written first, before the code

When implementing a big program or non-trivial algorithm, I start the file with comments that end up serving as an outline for the code I insert afterward. It helps clarify my thoughts about how I'm going to go about it, and of course keeps me from forgetting anything.

Re: Comments First (1)

Doc Ruby (173196) | more than 8 years ago | (#14147654)

I start a file with a description of what the contained "object" does. I don't put a lot of details in the beginning anymore, because I got tired of updating the comments whenever I changed the API or significant varibles/algorithms. I really wish my programming editor stored every line in its own record in a relational database, with separate tables for blocks, variables, class/function names and comments. I'd like to query for callgraphs, and more easily factor code. And I'd like to query for uncommented blocks. The side benefit of arbitrary indent/CR and other whitespace formatting also seems valuable, if out of the scope of this discussion. Someday.

Re:Comments First (1)

the0ther (720331) | more than 8 years ago | (#14147611)

This is great advice. Agree with you 100%.

There are loads of comments in Haiku... (1)

McCall (212035) | more than 8 years ago | (#14147509)

There are a ton of comments in Haiku [haiku-os.org] . Just take a look at their SVN [berlios.de] .

How to write stories (1)

Prince Vegeta SSJ4 (718736) | more than 8 years ago | (#14147510)

what they seem to need is a class on how to write stories, have you not seen the first sentence of THIS [slashdot.org] monstrosity?

OMG First Post (0, Offtopic)

minginqunt (225413) | more than 8 years ago | (#14147518)

KDE SUXX0rs. All the kewl kidz use teh Macs now!

---

Now that's a *great* comment. Lame, inaccurate, ignorable, irritating, worthless.

If I keep this up in my code, it'll be so unmaintainable by any other, I'll be secure in my job for life.

Martin

slashdot sucks (0)

Anonymous Coward | more than 8 years ago | (#14147527)

start an account, start a blog, and post your articles to mods to have posted as "stories"

Comments Not Needed... (0)

SparafucileMan (544171) | more than 8 years ago | (#14147538)

...if you wrote your code clearly enough. Any well written code is as easy to read as comments and is more informative. By doubling up and reading the comments as well, you're just wasting your time.

Of course, alot of code isn't well written so comments ("pseudo code") is necessary just to understand it. The sign of either a bad programmer or a system or language that is too complex.

The name of the game is find the right language, and you won't have to juggle two or five poorly written languages.

Haiku? (3, Funny)

Daedala (819156) | more than 8 years ago | (#14147544)

Remember the seasonal reference!

Begin declaring
Global integers, constant
As the winter rain

Check for null values
That will cause problems later
Cherry blossoms fall

One good reason (2, Informative)

Billosaur (927319) | more than 8 years ago | (#14147553)

You should write comments because some day you're not going to be doing your job anymore, perhaps because you started your own rock band, or won the lottery, or the company decided they could get someone cheaper to do your work. In any case, some unfortunate soul (and I've been this person more than once) has to come in and maintain and expand your code. And in most cases we're bright and we know our languages pretty well, but we can be a little slow on the uptake. In the end, we stare at your code and ask, simply: What the freak is going on here?!?!? Because we are not mind readers, and if we were, we probably wouldn't want to touch your mind because... ewwwwwwwww!

Does this mean you have to do this?:

my $i = 0; # initialize variable $i

No! We're not retarded... we think. But if it's not trivially obvious what you're doing somewhere in your code, please feel free to let us in on it. We would appreciate it.

Commenting has its uses. (1)

Malpheus (934478) | more than 8 years ago | (#14147556)

As an engineering student in college, failing to comment in my code is equivalent to failing at life. Our profs say it's common courtesy to comment code, especially in industry. As one who has had to read the code of others, I can say it does help at times. So keep commenting, if only for the stupid people.

Javadoc and XDoclet as models (1)

coyote-san (38515) | more than 8 years ago | (#14147562)

I've written a lot of comments, and most of it was useless. It helps when you're looking at the code itself, but you missed the larger context unless every comment was mindnumbingly detailed. That type of comment is a pain to write and essentially unmaintainable.

Javadoc (and similar well-supported systems) is godsend. You still want to have some comments within your code, but the real power is in the generated documents that give you the larger picture. It's not complete -- you still want to know the overall architecture and design -- but many days I would rather have empty Javadoc (with nothing but links to the classes used as parameters and results) than well-written but isolated comments within the code, especially if reasonably sane class and method names are used.

XDoclet takes this one step further. The comments don't just produce useful documentation, they produce useful configuration files and even related source code.

Explain Things That Need To Be Explained (1)

Py to the Wiz (905662) | more than 8 years ago | (#14147569)

Ive been in enough classes this year (well below my level.. dammit, I need the "letters") that Ive come to the conclusion that introductory programming courses are taught all wrong.

Write 5 lines. Write 20 lines. Write 100 lines. Of useless and pointless code.

What should be done is: Take this 1000 line programme. Add on 5 lines. Add on 20 lines. Add on 100 lines. Beacuse that would require being able to read code, too. Being able to understand what is already there is frequently more then half the battle. Saying "What the fuck does this mean?" a few dozen times is the only way to get to write comments. Being a sysadmin, rather then a full time programmer, this took me litteraly years to learn. And it was usualy "What the fuck were you doing here, brain? Dammit, one of these days were going to have to start commenting our code."

About 6 months ago, I read through a project request on one of these ebay-for-coders sites. Language optional; 1 comment per 5 LOC, but if using Perl, 1 comment per 2 LOC.. With requrements like that you are only asking to get BS comments like "Print X to the console".

good code is not self-documenting (2, Insightful)

petes_PoV (912422) | more than 8 years ago | (#14147578)

this is a common mistake that some beginners and most managers make. It usually only survives in their minds until they have actually read someone else's (supposedly) self-commented) code.

As the OP says, code will only ever tell you the "how" not the "why". As in this snippet:
i++ ; increment counter
while trivial, it tells you nothing about why you wish to increment the counter. Ada,C(++) or any other high-level language is always limited to this.

The best comments are a summary at the start of a block of code that describes the autors intent. It should have correct spelling and grammar. if the coder can't even get the coment right - the code is probably wrong, too.

Definitely Haiku (1)

Rorschach1 (174480) | more than 8 years ago | (#14147581)

comments in haiku
not for any good reason
I was very bored

(And yes, I have done this. The bit above and several others are, as far as I know, still in some shipping management system for a certain multinational mining corporation.)

/* Drunk -- fix later */ (2, Funny)

Cobalt Jacket (611660) | more than 8 years ago | (#14147582)

© Leo Plotkin

Even Worse (1)

PlayfullyClever (934896) | more than 8 years ago | (#14147584)

I used to grade student's code as a TA at my university, and I'll tell you what is more annoying than NO comments, this:

printf("Encrypt message...");/* print "Encrypt message..." to the console */

and then followed by about 150 lines of uncommented spaghetti code

Re:Even Worse (1)

CynicalGuy (866115) | more than 8 years ago | (#14147631)

Although it does make it easy to tell when the student copied the assignment from someone else.. :)

It should be hard. (1)

www.sorehands.com (142825) | more than 8 years ago | (#14147597)

It was hard enough to write, so it should be hard to read.

Anyways, code is obvious to a REAL PROGRAMMERS [sorehands.com] .

Obligatory... (1)

Saeger (456549) | more than 8 years ago | (#14147600)

...I don't comment code for job security. Besides, comments are for the weak; good code should be self-documenting (but my code isn't good either, because I have to obfuscate it... again for the mythical job security).

Intelligent response //add to this (1)

0110011001110101 (881374) | more than 8 years ago | (#14147601)

Hello slashdotters //make this wittier

//put more believable words in here, sometimes larger words
//convince the /. crowd that Im actually intelligent
I would like to say that commenting code has helped me many times to more completely understand the crap my co-workers produce.

//TODO: make the following post an actual haiku, to amuse
//the more advanced crowd
Haiku comments would be disastrous

//TODO: add funnier sig, this one sucks

!- -pretty words go here- - (1)

kevin.fowler (915964) | more than 8 years ago | (#14147604)

working in XML in content development, I really can't add personal flair to code; many cooks are working on one pot. I am however a firm believer in commenting so that everyone in your project knows what the hell is going on. much more useful than having one comment per 3 lines of code like I had to have in college projects. (3 points off my final because one of the comments read "my sister was once bitten by a moose")

Comments (1)

Live_in_Dayton (805960) | more than 8 years ago | (#14147608)

I saw the RSS title and I thought it was about writing comments on /. Am I spending too much time on this web site?

how to write comments (1)

BushCheney08 (917605) | more than 8 years ago | (#14147615)

1) Press 'Reply' button or click 'Reply to This' link.
2) Type witty reply/comment/troll in box. Don't forget to include a subject.
3) Click 'Submit' button. Note: Under no circumstances should you click the 'Preview' button!

The code was hard to write.... (1)

mcsporran (832624) | more than 8 years ago | (#14147617)

Therefore it should be hard to read.....

Docs more important... (1)

cosinezero (833532) | more than 8 years ago | (#14147622)

I think documentation goes a lot further than comments. Chances are, with good docs and proper unit testing, I never have to read the source on your object.

Comments need to include rationale (0)

Anonymous Coward | more than 8 years ago | (#14147624)

Hi - I have heard this "proper code does not need comments" idea for years. What this ignores is that many times there are multiple ways of implementing something. In such a case IMO it is very helpful for the original developer(s) to explain why they chose a certain method / algorithm over another. As times goes on, things often change (price of storage, memory, etc) and the original factors may no longer be as important in years to come. A related area is when there is a bug in the software (compiler or interpreter etc) that is being coded around since future versions may fix the bug or provide an entirely different method.

TWR

Various commenting style... (0)

Anonymous Coward | more than 8 years ago | (#14147625)

Well, comments are sometimes needed, but sometimes...
// Beginning
// Middle
// Endpart
//  IMPORTANT HERE

or something in one of the books. A page explaining workings of a program. Then a page of listing of the program, about 60 lines of comments on how it's supposed to work. Repeated from the previous page. Then 5 lines of actual code total, quite self-explainatory too.

Or:
y = x - x - x; /* Just you dare changing this!!! */

or:
<!-- A79BD69D8DD324F9DF -->

or:
for(i=0;i<maxT;i++){  /* This is a very tricky   *
unit[i]=another[i]%c;  * part so pay             *
if(!unit[i]) break;    * close attention         */
}

There are quite a few more ways to comment the code in a creative way that will drive whoever reads your code nuts.

Self documenting (1)

Dun Malg (230075) | more than 8 years ago | (#14147630)

Real programmers write self documenting code, so even if your boss makes you put in comments, all you really have to do is repeat what the code says:

int x, y, z;
snizlr mfSnizzlr; //create variables
x = 10; //set x equal to 10
mfSnizzlr(y,z); //call snizlr to get y and z
for(int z1=0;z1 < z;z1++) //start at 0 and loop until z1 reaches z
{
y = (z>x) ? z : x; //set y to appropriate value
mfSnizzlr(y); //y back to snizlr
}

return(y); //return y

see? easy!

Writing Comments (1)

Nom du Keyboard (633989) | more than 8 years ago | (#14147632)

Writing comments helps you understand that you know what you're doing.

And useful later on when you need to fix your own code after plenty of time has passed allowing you to forget how clever you were in the first place.

If you don't comment it will come back to haunt u (2, Interesting)

gasmonso (929871) | more than 8 years ago | (#14147642)

Commenting code is good on several fronts. Firstly, even the programmer can't remember what the hell he did just a few weeks ago, let alone several months or years. You will thank yourself. Secondly, anyone else who has to modify that code will track you down to explain something if it's not commented. If you use source control, they will find you. And thirdly, it's easy to do while you're coding and not after. It's almost a freebee.

gasmonso http://religiousfreaks.com/ [religiousfreaks.com]

General comments guidelines (1)

Foofoobar (318279) | more than 8 years ago | (#14147650)

I like my comments to have brief description and show example of usage to cover the 'hit by a train' scenario. Also with good comments, you don't require as much documentation... which is a shame because WE ALL LOVE to write documentation! /* getFunction(array,int);
      desc: Function is described here
      usage: this->getFunction(names,number); */
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>