×

Announcing: Slashdot Deals - Explore geek apps, games, gadgets and more. (what is this?)

Thank you!

We are sorry to see you leave - Beta is different and we value the time you took to try it out. Before you decide to go, please take a look at some value-adds for Beta and learn more about it. Thank you for reading Slashdot, and for making the site better!

Comments are More Important than Code

timothy posted more than 9 years ago | from the if-you-disagree-provide-comments dept.

Programming 1021

CowboyRobot writes "I was going through some code from 2002, frustrated at the lack of comments, cursing the moron who put this spaghetti together, only to realize later that I was the moron who had written it. An essay titled Comments Are More Important Than Code goes through the arguments that seem obvious only in hindsight - that 'self-documenting' code is good but not enough, that we should be able to write code based on good documentation, not the other way around, and that the thing that separates human-written code from computer-generated code is that our stuff is readable to future programmers. But I go through this argument with my colleagues, who say that using short, descriptive variable names 'should' be enough as long as the code is well-organized. Who's right?"

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

Even more annoying... (5, Funny)

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

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 more annoying... (2, Interesting)

eobanb (823187) | more than 9 years ago | (#12354489)

Well then, just employ a code comment moderation system.

Re:Even more annoying... (2, Funny)

FuzzyBad-Mofo (184327) | more than 9 years ago | (#12354598)

And a metamod system to deal with the inevitable poor moderation. Hmm, Slashcode as a source control system? Scary thought..

Re:Even more annoying... (5, Insightful)

Klar (522420) | more than 9 years ago | (#12354521)

hah I also grade as a university TA, and let me tell you what is more annoying than that... people who don't know how to indent their code, and want you to help debug it! Ahhhhh!!!!!

Re:Even more annoying... (2, Interesting)

zachtib (828265) | more than 9 years ago | (#12354571)

Thats why I love eclipse, auto-indenting (Ctrl Shift F) comes in handy when fixing other peoples' code

Re:Even more annoying... (2, Insightful)

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

Emacs will handle that too...

Re:Even more annoying... (2, Funny)

blueadept1 (844312) | more than 9 years ago | (#12354574)

I'm really sorry dude. I thought you didn't know what print was :/

Just flaunting my leet ski11z. Keep it uber.

Re:Even more annoying... (2, Funny)

s100w (801744) | more than 9 years ago | (#12354621)

Some of your graduates most have taken jobs at my company.
/**
* Gets the name
* @returns String name
* @author RG
* @throws Exception
* @param boolean
*/
public String getName(boolean b) [
if (b) {
return magicalSideEffectGetter();
} else {
return name;
}
// Changed by RG 10/18/1999
// Re bug fix #1044
// return name;
}
Of course, the old code, revision date, and author is in CVS. And the bug is in the bug database, but ... more comments are better, right? In the real world, this method would be about a page long.

Gotta document that code... (5, Interesting)

TripMaster Monkey (862126) | more than 9 years ago | (#12354435)

From the Summary:
...I go through this argument with my colleagues, who say that using short, descriptive variable names 'should' be enough as long as the code is well-organized. Who's right?


You are. No question.

I have a saying I like to use when people (usually managers) try to persuade me to take the quick/cheap way out:


"Any time/money you save by cheaping out now, you'll wind up having to pay back twice over on the back end."


I've yet to see this maxim disproved, and it's just as applicable to coding as it is to anything else. Your colleagues are certainly correct when they state that the code must be well organized, but this simply isn't enough. If you don't put in the necessary time (minimal, really) to properly document your code, you'll wind up spending a lot of time trying to figure out just what you did and why. Also, even if you can remember exactly what your code is all about, the guy that comes after you probably won't...proper documentation is professional courtesy. I suppose they'll learn after they spend a few hours puzzling over a piece of old code (that's how I learned...:P ). Sooner or later, not documenting properly will bite them in the ass.

Re:Gotta document that code... (5, Insightful)

Fjornir (516960) | more than 9 years ago | (#12354446)

The canonical form of your maxim is "If you don't have time to do it right the first time, when will you find time to do it again?". The correlary is: "The problem with quick and dirty is that dirty remains long after quick is forgotten."

Re:Gotta document that code... (2, Funny)

eobanb (823187) | more than 9 years ago | (#12354459)

Judging from your indenting, I'm sure glad I don't have to read YOUR code.

Re:Gotta document that code... (1)

LogicX (8327) | more than 9 years ago | (#12354481)

I don't see why people still cry about large indents -- If you're serious about your job, get a 21" monitor, and run 1600x1200 or higher; more on the screen, who cares about a now tiny indent.

Re:Gotta document that code... (2, Insightful)

Fjornir (516960) | more than 9 years ago | (#12354610)

...how does that work when I need hardcopy again?

I actually agree with you though -- as long as the indent character in question is a tab. People who want to indent with spaces need their heads examined.

Re:Gotta document that code... (1)

FuzzyBad-Mofo (184327) | more than 9 years ago | (#12354612)

My preferred solution:

set ts=4

Re:Gotta document that code... (5, Insightful)

RootsLINUX (854452) | more than 9 years ago | (#12354510)

I agree. Giving your variables descriptive names is a good practice, but it's not nearly enough "commenting". If you have a piece of code that manipulates the values of those descriptive variables with bit masks to spit out a value, how is someone supposed to know what you just did? I think the adage "you don't document your code, but you code your document" is a little extreme, but it gets across the importance of code documentation. I'm working on an open source project of my own right now. I went back to modify a piece of code that I hadn't touched for nearly 4 months, only to make absolutely no sense of what the hell I was doing there. Luckly I commented it extremely well so after reading the comments I was able to get that "Oh yeah..." feeling and make the appropriate modifications without breaking the code. Lesson: commenting code may take you some more time now, but it's going to save you a hell of a lot of time later.

On that topic, what are some good examples of well-commented code? Rather than just see words, I'd rather see real-life applications of these practices. For starters, here's typically how much I comment my code: Allacrost source code [sourceforge.net] (note: not all files were written by me, by I try to stress heavy commenting on the rest of my team)

Re:Gotta document that code... (2, Insightful)

Xyrus (755017) | more than 9 years ago | (#12354633)

Comments are essential to maintaining any project.

It's annoying when I go to the person who wrote a chunk of code fom a couple months ago to ask them some questions, they look at the code and have no idea why they were doing what they were doing.

I've always followed the philosphy that I should write and comment code so that someone who wasn't a programmer could read it and understand what was going on. This makes it very easy to go back even years and know exactly what the code was doing and why it was doing it.

But you need to write good comments and good code. I've actually seen this in code: /**
Gets an array.
@return An array.
*/

Array GetArray() ...

The other one I live seeing is data structures containing non-descriptive field names: //Holds temporary data
struct TmpData
{
int a;
int b;
float c;
};

Completely useless.

Good code and good comments makes everyone's life easier. I've seen a lot of good code, I'd like to see a lot more good comments as well.

~X~

Re:Gotta document that code... (5, Insightful)

snorklewacker (836663) | more than 9 years ago | (#12354641)

You are. No question.

Hello. I question. Look, if you need comments to explain the code flow because your method spans four screens and has six levels of conditionals in two levels of loops, all the comments in the world won't help you.

Especially if you change the code and now the comments are wrong

I have had the joy of maintaining lovingly commented code with all these huge blocks at the start showing what args get passed and what happens, and I can't understand a god damned thing about what it's doing, because the code all looks like
(void *((ebuf->qs) > VRT_FBUF) ? etranf(&q) ...
All generalisms are wrong.

Use long variable names (2, Funny)

Joey7F (307495) | more than 9 years ago | (#12354439)

Just go ahead and use the long names, that alone will reduce documentation/commenting

--Joey

Nah (5, Funny)

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

Variable names should be proportional to the size of their scope within the code.

Re:Use long variable names (1)

agm (467017) | more than 9 years ago | (#12354579)

I always prefer long variable names over short or abbreviated ones. The only exception is "i" and "j" for loop counters.

They may take longer to type, but I'd much rather tap away at a few more keys that wonder what the variable is for. And that's when reading my own code, the problem is worse when it's someone elses code. The same applies for class properties and method names.

Re:Use long variable names (1)

The Snowman (116231) | more than 9 years ago | (#12354603)

Just go ahead and use the long names, that alone will reduce documentation/commenting

I think variable names should answer "what," not "how." As in, what does this variable represent? Comments describe how it is used. Using concise (not necessarily short) variable names make sure you can look at a variable and say "hey, that's a window handle, that other one is a user's login, etc." Variables may have more complex usage, but usually those will be classes and have their own documentation anyway.

Re:Use long variable names (1)

techno-vampire (666512) | more than 9 years ago | (#12354640)

Short or long isn't the issue. Make them descriptive. If you're calculating the rent on an office, calling it "rent" should be enough. If you have to calculate three different rents and total them, "office_rent," "computer_rent," and "copier_rent" will help you keep track of which is which. Put in as much as you need to help the next programmer know what's going on, but making them long just because you can doesn't help.

Comments more important? (5, Funny)

Rollie Hawk (831376) | more than 9 years ago | (#12354441)

Has he read the ones here?

huh, just like /. (4, Funny)

eobanb (823187) | more than 9 years ago | (#12354442)

...where comments are more important than articles.

Re:huh, just like /. (1)

smellygeek (702897) | more than 9 years ago | (#12354627)

What articles?

Perl POD Documentation (2, Interesting)

LogicX (8327) | more than 9 years ago | (#12354444)

How about Perl's POD Documentation? I do a lot of hacking of Matt Simerson [simerson.net] 's Mail::Toaster [tnpi.biz] and Nictool [nictool.com] projects, and I find that the Perl POD Documentation system, combined with well-named variables is easy on the eyes, and leads to it being well interpreted by an outsider.

Re:Perl POD Documentation (1)

Roguelazer (606927) | more than 9 years ago | (#12354497)

Is that like RubyDoc [rubydoc.org] ? RubyDoc basically goes over your source code and extracts classes, functions, etc, then parses nearby comments (if present) and auto-generates nice documentation.

Documentation encourages complacency of thought (0)

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

Comments can be misleading, misinterpreted, out of date, or just plain awful.

Code is self-documenting.

Re:Documentation encourages complacency of thought (3, Interesting)

Fjornir (516960) | more than 9 years ago | (#12354498)

"Don't get suckered in by the comments -- they can be terribly misleading. Debug only code."
--Dave Storer

Re:Documentation encourages complacency of thought (1)

electricsheep7 (794184) | more than 9 years ago | (#12354595)

I second this. Provided that classes and method contracts are adequately documented, the actual code in them should be sufficiently expressive. Too much documentation tends to hide what the code actually does ;)

Of course, I'm generally liberal with the FIXME and BUGBUG markers.

Re:Documentation encourages complacency of thought (1)

CreateWindowEx (630955) | more than 9 years ago | (#12354602)

In fact just today I saw one sort of classic case where there was a comment indicating a problem that had lingered even though the actual problem had been fixed.

Except for the use of comments for marking "document structure" as well as brief "overview" for more complicated modules, I view comments inline with code as being required only if something is tricky, questionable, or some other hackery. Usually the time spent commenting the actual code would better be spent refactoring it and cleaning it up.

I think someone has a quote about code being primarily intended to be read by humans and secondarily by compilers, although surely phrased in some more clever and pithier way...

obg... (0)

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

I spent a minute looking at my own code by accident.
I was thinking "What the hell is this guy doing?"

with thanks to bash

Re:obg... (0)

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

http://www.bash.org/?6824 [bash.org] http://www.bash.org/?6824

apperently something went wrong with that post...

Comment. (2, Insightful)

stealth.c (724419) | more than 9 years ago | (#12354454)

Always comment. Always. I'm not a career coder, but I've done enough to know that if it's a project of any noticeable size at all, and you intend to read the code later, take the extra few seconds and COMMENT THE STUPID THING. It makes life a lot easier. The only thing that probably doesn't need commenting is a simple BAT file or a shell script. Comment!

Re:Comment. (1)

Fjornir (516960) | more than 9 years ago | (#12354569)

I know you qualified it with "simple BAT" and presumably by extension "simple shell script" -- so please don't think I am arguing with you... I would say however that the non-simple BAT/non-simple shell scripts need comments more than the average piece of C code, for instance.

C is very expressive, has a number of well-known idioms, and so on... Shell scripts are generally quite terse and often more in need of commenting.

Opinion... (1)

duhasteifersucht (859131) | more than 9 years ago | (#12354456)

I think having comments in your code is a matter of preference. I find it nice to have as few comments as possible so i can read the code better.

Obviously thats my preference, but i feel comments are optional (unless dealing with really complicated code)

Re:Opinion... (1)

LoztInSpace (593234) | more than 9 years ago | (#12354514)

I agree. Code should be pretty obvious and the use of decent names, structure etc make it so. Of course there will be some gnarly bits that need special treatment, but I tend to stick with that
I think a more interesting discussion would be the equivalent of comments & documentation for and from non-coders such as BAs & DBAs, project managers etc.
For example:

UML/Class diagrams
Data models
Business rules
Functional manual
Lexicon

All more interesting.

Re:Opinion... (1)

duhasteifersucht (859131) | more than 9 years ago | (#12354546)

i have no trouble commenting if i am coding for someone else, but im not going to have more comment then code, as people have requested in clarification of code i write. thats just really annoying to be quite honest

Re:Opinion... (0)

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

...right... Because obviously you've got some magic super power which lets you re-insert comments that were never added in addition to the "hide comments" filter that any half-competent coder could make with a regular expression in, say, 10 minutes (or two of googling).

Fucktard.

Re:Opinion... (0, Troll)

duhasteifersucht (859131) | more than 9 years ago | (#12354617)

Or you could just be smart enough to know what the code does without the comments? tool

Switch from C (1)

python_kiss (876709) | more than 9 years ago | (#12354457)

Use Visual Basic! More Comments and zero code.

development process (1)

phloydphreak (691922) | more than 9 years ago | (#12354468)

A good development process with commented function names and function purpose as the framework for the project will assist in the coding as well as provide more than adequate commenting on a project (shouldnt code the how, only the purpose). Its workes for me in college (sr. UIUC), lets hope it continues in the business world...

Re:development process (2, Interesting)

frikazoyd (845667) | more than 9 years ago | (#12354556)

You are absolutely right. Some of the better design processes (to me) have involved turning the initial documentation into skeleton code, then writing comments around all the functions and classes that describe exactly what the program is supposed to do. Not only does it provide for excellent commenting and understandable code, it is immensely helpful in the writing of these functions.

Having a function named "getKey(row r)" with a comment saying /*retrieves the key 'SS#' from row r*/ may seem like overkill at first, but people who go over my work later don't even have to read the function for the code (unless they suspect the function is the source of a bug). They know what it is supposed to do, and a written out comment is generally clearer than a pre:post: with the bare minimum of description that some people prefer.

Fine with some comments, Don't over do it (1)

bigbinc (605471) | more than 9 years ago | (#12354470)

I work with java, with javadocs. There is nothing more frustrating than reading a 500 line program and having the actual represent 20 lines with 480 of the lines filled up with comments. Just don't over do it. Another thing, in school they teach you, "You should comment every line". That is silly, not every line needs comments. I believe in a black box approach to your programs, if you can comment outside of the function and describe what is going on inside of the different blocks. I can't easily reuse that function if it is properly commented. I don't want to know what is going on, but if I know the arguments, the return-type, I am ok.

Re:Fine with some comments, Don't over do it (0)

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

I work with java, with javadocs.
You say that first, as if it should lend you some credence.

There is nothing more frustrating than reading a 500 line program and having the actual represent 20 lines with 480 of the lines filled up with comments.

Here's a tip:

egrep -v "^#" file | less

If you don't use # for comments, adjust the cmd line.

Comments are valuable, but good code essential (1)

Eternally optimistic (822953) | more than 9 years ago | (#12354472)

When you write bad code, good comments won't save you. The other way can sometimes work. Spending all your time on comments seems like only talking about solving an engineering problem, not actually doing it.

And this, my friends, is why offshore outsourcing (1, Troll)

melted (227442) | more than 9 years ago | (#12354475)

And this, my friends, is one of the reasons why offshore outsourcing is doomed. You understand comments are important. For people in India schedule is far more important than comments. So they'll cut&paste shit all over the place and leave it uncommented. If you happen to have to work with it, your hair will turn gray pretty quickly.

Re:And this, my friends, is why offshore outsourci (2, Insightful)

John Seminal (698722) | more than 9 years ago | (#12354555)

And this, my friends, is one of the reasons why offshore outsourcing is doomed. You understand comments are important. For people in India schedule is far more important than comments. So they'll cut&paste shit all over the place and leave it uncommented. If you happen to have to work with it, your hair will turn gray pretty quickly

I disagree. India has more engineers than the USA. And these are smart people. Some of them already know english, and others will have to learn. India is a country with too much poverty and so little oppertunity, that when a young kid is given a chance, he'll learn it all. They are lean (paid little) and hungry (willing to learn). In the USA, we expect $100 an hour to consult, one place I worked at hired an Arthur Anderson consulting team and the lead got over $300 an hour. I bet he would be *insulted* to have to work for $20 an hour. Are you going to tell me that the guy in India won't take that wage?

If it means people in India will have to learn english, they will learn english the same way they get their engineering degrees. They will study their asses off like their lives depend on it.

If people in the USA have half a chance, now is the time to take advantage of it and produce a better product than they do in India. Leverege every advantage we have, because the competition is getting better.

We could say how the Bush administration is screwing us, and to a large extent they are. We never should have let factories leave the USA to mexico. We never should have let outsourcing happen. I hope future presidents start raising the tariff, and force American companies back in the USA. But maybe we need to get a little more lean. It is hard for the avarage employee to give a fuck when you see the CEO get a bonus when he lays people off, or scum like enron managment steal the pensions of employees, but what other option do we have? Change the tax code to tax the wealthiest at a higher rate and pump that money back to the poor? Maybe raise the luxery tax rate? Increase the estate tax? Break monopolies?

Re:And this, my friends, is why offshore outsourci (0)

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

Agreed. I am currently (this very night) going through an assortment (few hundred) of php documents that run a friend's business website.

He had it done by a company that eventually outsourced it to.. guess.. India.

Within an hour I've found 3 non-working subroutines in the administrator login menu, 4 unprotected directories on the webserver containing files which hold among other things the SQL database login/password and not ONE stinking bit of the code is commented. There's cut/paste jobs abound, even containing referances to free php-script type sites.

It's an absolutely horrible job. Although the site graphics/layout is quite excellent. =)

I have a feeling the company hired produced the color scheme and layout then outsourced the backend.

Write code like someone else will maintain it (4, Interesting)

John Seminal (698722) | more than 9 years ago | (#12354477)

that using short, descriptive variable names 'should' be enough as long as the code is well-organized.

This works for code I write that nobody else will ever maintain. Even then I can get tripped up, I'll have to lean back in my chair and try to remember what I was thinking when I wrote the code.

But if you write code you're getting paid for, or code for an organization, anything but personal stuff, write good comments. Variable names might give a good idea about what data the variable holds, but it does not tell us much about how it is used.

When I took my first programming class, the most frustrating part was the documentation. I thought it was retarded and stupid and a waste of time. But now I realize it is very important once you write something more significant than "Hello World".

Re:Write code like someone else will maintain it (0)

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

I've often tried to go through my code and attempt to remember what I was thinking.
I find though, that it really just depends on the strength/type of pot I was smoking at the time. Certains types of pot cause me to code different ways.
Just an FYI, is all.

No such thing as too many comments... (0)

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

Good organization and descriptive variable names are no substitute to actually noting what the heck you're looking for or trying to accomplish. Checking a bit flag with a nice name (such as "input_recvd") is not nearly as useful to the maintenance programmer as a comment which says "test bit flag set by keyboard input routine - "1" value indicates input complete"

Re:No such thing as too many comments... (2, Insightful)

Desult (592617) | more than 9 years ago | (#12354585)

You need that comment?

if (kbd_input_rcvd)
{
process_input();
}

is not clear?

I think properly modularizing your code (breaking process_input() into its own function), and properly documenting the modules (defining good documentation of input, output, exception conditions, return values, side-effects) is more effective than writing verbose comments (like the one you've noted) in poorly segmented code.

This whole discussion is a bit short sighted. The better and clearer your code is, the fewer comments will be necessary. The more useful comments you add, the less time will be necessary parsing and understanding clear code. The better your design overall is, the less code reading overall will be required, because you'll have documentation outside of your code that explains how the system works, and where you need to go make changes. Saying one is more important than another is silly.

Riiiiight... (1)

Etherwalk (681268) | more than 9 years ago | (#12354485)

> But I go through this argument with my colleagues, who say that using short, descriptive variable names 'should' be enough as long as the code is well-organized.

Yeah, it should be enough, so long as you're writing a very well known algorithm. Like, say, heapsort. Small functions with no side effects, good variable names and scopes as limited as is reasonable for each variable. I mean, technically, the code tells you exactly what the code does.

Sheesh. Comments important. How important they are varies with the algorithms you're implementing. But they're important. Clear code with less commenting may be more valuable than complex code with more commenting. That's hard to call. But in the end, you have to know what code says. And if it's clear enough from the code, fine, then the code IS your comment. But that's not a safe habit to fall into, because then you have the mentality that code is always enough for a comment. This gets you into trouble. (Big trouble.) See any piece of complex C code. =)

Not necessarily comments... (3, Interesting)

kwoo (641864) | more than 9 years ago | (#12354488)

In my opinion, comments are useful -- but literate programming is where it's at if you're looking for the best way to document your code.

Knuth did a lot of work in the area -- if I remember correctly, all of the sources to TeX are written in a style understood by the "web" literate programming tool.

There was also a good article by one of the Perl folks (Nathan Torkington? M.J. Dominus? Chromatic? I can't remember.) on POD, and how although POD wasn't literate programming, it was still useful. That article was great in that it showed a middle ground that may be more palatable to your non-LP-fanatic programmer.

That being said, I prefer full-on LP for large projects.

Re:Not necessarily comments... (1, Informative)

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

From Knuth's page:

The main idea is to regard a program as a communication to human beings rather than as a set of instructions to a computer. Your program is also viewed as a hypertext document, rather like the World Wide Web. (Indeed, Knuth used the word WEB for this purpose long before CERN grabbed it!)

CWEB is a version of WEB for documenting C, C++, and Java programs. WEB was adapted to C by Silvio Levy in 1987, and since then both Knuth and Levy have revised and enhanced the system in many ways, notably to support C++ and ANSI C. Thus CWEB combines TeX with today's most widely used professional programming languages.

look it up people...

Something i notice (5, Insightful)

bmajik (96670) | more than 9 years ago | (#12354490)

i do a lot of code reviews at work and nothing makes me happier than good comments.

but just putting a bunch of blocks of comments that are like "get customer", "build record", etc are basically useless. If you use programming by intent then its more or less obvious that the code

GetCustomerFromDatabase(foo)

is going to do something with a database and get a customer. a comment telling me that is useless.

what i like to do is write a few paragraphs of text at the top of a function. it explains my general approach, why im doing certain things the way i am, why im not doing other things, and why the function even exists.

essentially the comments should be enough that anyone that knew the problem space ought to be able to read them and come up with more or less a similar implementation.

then, in the body of the method anytime i do something that i feel isn't completely obvious, i put a 1 or 2 liner infront of, i.e. "we have to do this because zergs are sensitive"

the end result of all of this is that code reviews can see what you were thinking at the time the code was written.. and you're documenting assumptions about the problem, the apis, your understanding of the language, etc, all right in the code. it makes finding errors pretty easy.. someone that can't even read source code can read the comments and get an idea of the correctness of your approach.

Doxygen (1)

Umbral Blot (737704) | more than 9 years ago | (#12354499)

The last word in documenting your code is doxygen. Especially the @author tag so you know who to yell at. I find that keeping individual functions short and then documenting what each one is supposed to do / take as parameters / return is better than comments within large blocks of code. What I hate though are large blocks of commented code. I guess sometimes the developers is too timid to remove old code, but seeing them always makes me wonder if the new code really works, and if so why is the old code still there.

News? (0)

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

Maybe in 1970, but nowadays commenting is so ingrained in the coding process that code review and similar activites don't even start unless the code has sufficient commenting. This article is really only relevent now for start-ups were coders are not necessarily answering to any company guidelines, but any decent start-up knows they need a decently commented code-base (look at any of the successful open source projects out there).

A rule of thumb... (1)

pdbogen (596723) | more than 9 years ago | (#12354509)

But impossible to follow, is this:
Only comment the things that are hard to understand. The problem here is that you probably understand everything you're writing.

One way out might be to have a less-talented programmer give it the once over, and point out anything s/he didn't understand, for you to comment upon.

That, and as Dr. Stroustrup (Bjarne [att.com] ) said in class today, your code constructs should be directly analogous to what they are trying to describe in real life... But I guess this goes down to self-documentation.

Re:A rule of thumb... (1)

winkydink (650484) | more than 9 years ago | (#12354554)

Yes, knowing what to comment is a challenge. When I am actively working on a piece of code I find that I know it almost intuitively and comments are unnecessary. It's only when I go back weeks or months later to work on it again that I find the comments would have been helpful. Once I stumble through it a second time, I usually end up figuring out where the comments are needed. :)

My thoughts.. (1)

LordZardoz (155141) | more than 9 years ago | (#12354517)

I would say that reasonably well written and organized code does not need extensive documentation for you to come back to it later and maintain / extend it.

I would also say that such code by its self is totally inadequate if someone other then your self needs to come along and maintain / extend that code.

The real problem is not code in general, but code written under an immediately approaching deadline. I am in the ass end of a crunch that has gone on a bit longer then anyone would have liked it to. Code written this time last year is still pretty good. But code written in the last few months is pretty rough from a long term maintainability standpoint.

Therefore, I suggest this:

When writing new code, make it self documenting, and comment at your discretion.

When fixing bugs frantically in the ass end of the project, Comment extensively.

END COMMUNICATION

dont be lazy (1)

mrterrysilver (826735) | more than 9 years ago | (#12354524)

people don't comment code for two reasons:

1. they're in a rush
2. they're lazy

if you're being lazy then stop. add some basic comments which will help someone else, or even yourself when you come back to the code in the future. long names help but they aren't enough.

if you're in a rush then you probably should have started sooner. try to get more time if you can. if you rush thru the code now you're going to be in even more of a rush later with all the time you waste when you come back to your old code and have to painstakingly work your way it.

it depends (1)

joel2600 (540251) | more than 9 years ago | (#12354527)

if you're doing projects for work you'll tend to come under fire for taking too long and not meeting deadlines on time because you're taking all the necessary time to spend commenting, but then later on when you have to review your project to make additions or have someone else do the work you come under fire for not having spent enough time commenting
it's a real catch22 situation. plus since it's for work, having it commented or not really doesn't make much difference... at least to me.

Yeah, I love comments in large codebases (0)

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

Especially the ones like
/*
* WARNING - TRULY DISGUSTING HACK!!!
* Remove this ASAP after the show.
* Sorry, -mike.
*/
and you determine the checkin date was 1998.

Are you writing COBOL? (1)

jackb_guppy (204733) | more than 9 years ago | (#12354530)

There is a reason for COBOL.
There is a reason for C.
There is a reason for ASM.

Why cross the bound and use the worng one for wrong reason?

Comments ARE NEEDED to help understand "paragraphs" of code. Like the use of a subroutine or why the program got this point in processing.

Using variables like comments does not make the code easier to understand unless you are using COBOL.

Writing code like a(i++) =+ b(--j); does not make understanding easier. Nor always makes code run faster.

Writing comments like MOV AX,BX ; move AX to BX
makes the program more self documenting.

So in the end. You are mostly right. Adding comments where they are needed and ARE MEANINGFUL make future maintenance easier.

Now if only the next guy that fixes the code will actually REMOVE unneeded code and COMMENTS and place new correct ones in thier place.

Remove Comments (1)

mfh (56) | more than 9 years ago | (#12354564)

Now if only the next guy that fixes the code will actually REMOVE unneeded code and COMMENTS and place new correct ones in thier place.

I've found old comments in my PHP codebase before and sometimes they throw me off. To make a habit of deleting them when you're deleting old code can be tough. There is no way to distinguigh between old comments and new ones either... because all comments look the same.

Maybe it's time for XML to save us all?

Middle ground anyone? (1)

Transcendent (204992) | more than 9 years ago | (#12354534)

How about, comments for some, no comments for others!

But seriously, only comment what's complicated... anything easy (to other programmers, not just you) doesn't need to be.

I knew a guy who did pre-comments, where he would write out the steps for the loops, showing nesting and such before actually writing the code. It worked pretty good because you had an overall idea before you started digging through code.

Joel on Software (4, Interesting)

TrueJim (107565) | more than 9 years ago | (#12354535)

"There's a subtle reason that programmers always want to throw away the code and start over. The reason is that they think the old code is a mess. And here is the interesting observation: they are probably wrong. The reason that they think the old code is a mess is because of a cardinal, fundamental law of programming:
It's harder to read code than to write it."

From Joel on Software
http://www.joelonsoftware.com/articles/fog00000000 69.html [joelonsoftware.com]

Always comment.

What are programming languages for? (2, Insightful)

FhnuZoag (875558) | more than 9 years ago | (#12354536)

Why on earth do we even have commenting? I mean, we went through the whole programming language concept precisely to make instructions to computers human-readable. Ideally, commenting should be obsolete - the language and its syntax should make it obvious what needs to be done.

If it turns out that after all that, our code still isn't intelligible, then isn't this some monumental failure of C, Java, BASIC and the rest, whose whole raison d'etre is to make weird things make sense?

It is not math, it is not universally readable (2, Informative)

John Seminal (698722) | more than 9 years ago | (#12354608)

Why on earth do we even have commenting? I mean, we went through the whole programming language concept precisely to make instructions to computers human-readable. Ideally, commenting should be obsolete - the language and its syntax should make it obvious what needs to be done.

If it turns out that after all that, our code still isn't intelligible, then isn't this some monumental failure of C, Java, BASIC and the rest, whose whole raison d'etre is to make weird things make sense?

This is not algebra in high school where you lose points for not showing your work. This is the real world where an application might have 100's of lines of codes, maybe 1000's. It might be a bunch of classes in java working together. And then there is the logic, the work flow.

Plus, many companies use peer review for raises and advancement. If your peers have a hard time understanding your code, it will hurt you later.

Most people today don't work 30 years for one company. That means someone else will get stuck with your code.

Now either you will give that person months to go through all the code, to try and figure out how it works, or you will have code with comments that will help him hit the ground running.

You're Right (1)

B4D BE4T (879239) | more than 9 years ago | (#12354540)

As one of many, many people coding a very large software project, I have come to realize just how important comments are. My job is to test various pieces of code. Often the code is very poorly documented and I may end up spending days just trying to figure out how the code works. Even longer tracking down the bug(s) in it. If the person who wrote the code in the first place had bothered to comment it, I would spend A LOT less time (maybe no time) trying to figure out how the code works. But, since they skimped on comments (saving them a few hours), I'm left spending days working on the code, which costs the company a lot more in the end.

I don't typically comment code... (1)

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

.. but then I'm the only person that does anything with it really. But, I think these guys have the solution if you have a boss wanting the comments for true.c :

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

New Techniques and Better Programmers. (5, Insightful)

X-rated Ouroboros (526150) | more than 9 years ago | (#12354543)

If the comments are clear, a better programmer than you can come along later and say "What the hell was this guy doing?" and then replace your lines of fumbling crap with much cleaner/clearer code.

It's the difference between being able to see what you were trying to do vs. figuring out what you actually did.

Call it "Intent Oriented Programming" if you want.

Re:New Techniques and Better Programmers. (1)

iplayfast (166447) | more than 9 years ago | (#12354570)

Now that sounds like the voice of experience. :)

It depends on who is reading it (1)

peldrake (598184) | more than 9 years ago | (#12354547)

The amount of commenting necessary depends on the level of experience of those who will be modifying the code later. Experienced programmers will be able to figure most of the flow of the program (and therefore the pieces) fairly quickly, whereas junior programmers will require explaination.

They are (3, Insightful)

MarkusQ (450076) | more than 9 years ago | (#12354549)


Comments are a maintenence nightmare. They get out of sync with the code, and (especially when the code is bad to begin with) people read them instead of the code.

That means over time the human's understanding of what the program does starts to diverge from the computer's understanding.

This is not good.

If something is too hard to understand the way it is written without comments, it should be rewritten. You will save time in the long run, trust me.

Remember the old adage: Don't get suckered in by the comments--the bug is in the code.

--MarkusQ

Context (1)

spamspamspamspam (865770) | more than 9 years ago | (#12354552)

Comments give variables / methods / objects context.

intYear
is a reasonable choice of name for an integer variable denoting a year, but the year of what???

When code is first being written, the context is in the coder's head and everything is crystal clear and obvious. However, remove that immediate knowledge of the code, and the name intYear becomes far less descriptive.

Short of using 80 character variable names and destroying readability, you need comments to provide context so that the meaning of the value stored in the variable requires no interpretation. The same applies to methods, objects, etc.

Do what I do (1)

kushboy (233801) | more than 9 years ago | (#12354553)

Just write your whole program in comments.

Uhh... (5, Funny)

PrimeWaveZ (513534) | more than 9 years ago | (#12354557)

UsngShrtCmtsIsOftNotEnghAsOneMyNdToReWrtShtInTheFt r.

The problem isn't lack of comments (4, Insightful)

jjoyce (4103) | more than 9 years ago | (#12354559)

The problem is usually functions that are too long and are not orthogonal. Write short, orthogonal functions and you'll see your need for heavy commenting go away along with the need for long variable names.

Comments are only as good as its writer (0)

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

A story I heard from a coworker; some years back he worked as a coder for a school district in the state of New York.

He had a cow-orker who despite not knowing dittly squat about coding managed to got himself hired as a coder.

Knowing the said cow-orker is incapable of writing a single line of code, he and his OTHER coworkers had this git write the comments for their code instead.

Some time later the cow-orker left on his own accord and his replacement arrived. Their advice to this newbie was "Don't worry about the comments, they're all wrong."

Moral of the story, the comment is only as useful as the person that wrote it.

Comments are for feebs! (0)

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

If it was hard to write, it should be hard to understand!

Comment first, code later (1)

Knetzar (698216) | more than 9 years ago | (#12354562)

One way I've found to write well documented code, is to first write very general pseudo code, then for each block of pseudo code write really code (or a function).

So my code starts like: //initialize the variables //Execute the operation 1000 times //generate output //clean up //return

And each of those lines can either become a function, with more documentation within, or a small block of code.

This not only helps to force me to document (which I hate to do) but it allows me time to think of the algorithm that I wish to use, instead of the nitty gritty code.

Also, don't forget to liberally use whitespace. Separating blocks of code with newlines is an easy way to help people read your code.

Quality of comments (1)

SamMichaels (213605) | more than 9 years ago | (#12354565)

Sure, commenting is really important...especially for team projects. But you might as well make them quality comments. For example:
sam@dexter linux $ uname -a
Linux dexter 2.6.11-gentoo-r6 #1 Tue Apr 19 15:54:33 EDT 2005 i686 AMD Athlon(tm) Processor AuthenticAMD GNU/Linux
sam@dexter linux $ grep -ir " shit" . | wc -l
44
sam@dexter linux $ grep -ir " fuck" . | wc -l
57
sam@dexter linux $ grep -ir " sco " . | wc -l
82
sam@dexter linux $ grep -ir " microsoft" . | wc -l
168

Short, descriptive variable names Vs... (1)

iKaz (794177) | more than 9 years ago | (#12354567)

Short, descriptive variable names Vs well commented code are good to keep your employer dependent on your services since someone else that is forced to work on it will probably just wind up re-writing your code in the end to save time.

The Trouble with Comments... (1)

Who Man (671061) | more than 9 years ago | (#12354568)

Is that they often end up not matching the code.

I admit that I'm lazy and that's probably the biggest driving force behind not doing a lot of comments.

But, I find that fellow developers who do comment heavily end up doing this: they write some great code along with some great comments. Then the code is refactored about 20 times, and the comments end up completely out of sync.

And I find this code far more frustrating than uncommented code with meaningful variable names and small functions with meaningful names.

He's right (1)

fallendove (875598) | more than 9 years ago | (#12354573)

I agree. Thefor documentation.

Raskin (5, Informative)

kebes (861706) | more than 9 years ago | (#12354575)

JEF RASKIN, professor of computer science at the University of Chicago, is best known for his book, The Humane Interface (Addison-Wesley, 2000), and for having created the Macintosh project at Apple. He holds many interface patents, consults for companies around the world, and is often called upon as a speaker at conferences, seminars, and universities. His current project, The Humane Environment (http://humane.sourceforge.net/home/index.html), is attracting interest in both the computer science and business worlds.

For those who don't know (which apparently includes whoever is in charge of the linked article), Jef Raskin passed away this february. You can view the official press release, [raskincenter.org] or read more about [wikipedia.org] his contributions to computer science. I don't know when the article was written, but it seems it should mention that Raskin has passed away. In any case, his advice about commenting is good, just as his advice on user-interface design has always been lucid and helpful.

Comments as entertainment (1)

syynnapse (781681) | more than 9 years ago | (#12354577)

Somtimes its just plain old fun to read what people wrote in comments because you actually can get some insight into what was going on... its less formal than output.

seeing other's code-in-progress is always reassuring when there are things like:

/*good lord do i hate this effing function!
please god just make it wooooooork!*/

makes me feel not so alone.

as for variable names, when I was in my first comp sci class, I used to name variables obscene things (I was in highschool), which I thought was dandy until I realised that I'd have to go back and change everything so I could submit it to the instructor.
sigh..

Dude... (0)

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

"comment should be the default, with a way to signal the occasional lines of code."

Where do you work?

Jef Raskin (1)

veg_all (22581) | more than 9 years ago | (#12354586)

A swan song by one of the designers of the original macintosh, sadly deceased.

RIP [sfgate.com]

Indeed (5, Funny)

screwballicus (313964) | more than 9 years ago | (#12354591)

I was recently reading through some code I wrote ages ago and hadn't looked at in years, and wondering...dear god, what's this confused mess trying to do?

Imagine my relief when I came upon a helpful comment:

What the hell was I thinking when I wrote this?

All it took was one comment to put my mind to rest: no, it's not just me being stupid in the present. This code seemed this terrible back then, too.

Comments save the day once again.

code first, then comment (1)

KalvinB (205500) | more than 9 years ago | (#12354592)

If you need comments to understand your own code, then your code is sloppy and you should fix that problem first. Writting sloppy code is like having bad handwritting. Fix your handwritting. Comments get out of date and are a topic all their own. Someone who writes sloppy code will probably write sloppy worthless comments as well.

You should also code first because you know what a function is supposed to do. When it does exactly what it's supposed to do then comment it. Otherwise your comments will be more along the lines of wishful thinking and lead to more confusion.

You should understand the language well enough that you can keep in your head everything the code is doing and if not, understand the language well enough to be able to read the code to see what it's doing. Comments are not going to help you debug a function. You need to be able to read the code itself to be an effective debugger. Only once it is debugged can you confidently place in comments that say what the function does. Otherwise, it's just wishful thinking.

The most commenting I do before writing a function is a rough outline of the steps the function needs to go through. Only after the function is done and does exactly what it's supposed to do, do I comment it.

I've gone back to code (thousands of lines) I wrote in BASIC 10 years ago and can understand exactly what's going on despite there being no comments. Same with stuff I've written in C/C++. Comments are not essentional if you can read code like a book. Which, a professional programmer should be able to do.

www.wolf5k.com [wolf5k.com] has an obfuscated version of Wolf3D written in Javascript. I went through and deobfuscated the code, figured out exactly what it does and then commented it. I then took the deobfuscated version and translated it to C++. I did the same with the Gavare ioccc ray tracer although the results havn't been posted on-line yet.

Deobfuscated Wolf5K [icarusindie.com]

If you want practice reading "bad" code, deobfuscating programs is great practice.

Ben

BS (1)

isny (681711) | more than 9 years ago | (#12354600)

Tell that to the boss when the code is due. You will soon learn what is REALLY important in the real world.
Without working code, there is no product. Without product, there is no money. Without money, hello unemployment line.

There is a middle ground. (1)

Some Random Username (873177) | more than 9 years ago | (#12354618)

I hate seeing code with no comments, especially when its not immediately obvious what a piece of code is doing. But I hate it just as much to see code full of useless comments explaining what the code is doing, when the code should be explaining it just fine. Stuff like:
i++; /* increment i */
makes me want to kill someone. Worse yet, when its:
i++; /* increment i - Bob Nov 2002 */
as if comments are an acceptable form of version control. It takes a bit of practice to find the right middle ground, where you make sure your code is easy to understand and doesn't need comments, but the tricky spots that just can't be made easy to understand are commented well.

At least comment the methods... (0)

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

At least that's what someone who comments told me. :)

Variable Names (1)

slobber (685169) | more than 9 years ago | (#12354631)

using short, descriptive variable names 'should' be enough

Aren't they on the opposite ends? I find it much easier to have descriptive variable names which are relatively long (~25 chars in C++). Not all variable names need to be that long (most local variables don't), but I often find that using long descriptive variable names makes comments unnecessary.

Also, I don't think there is some magic ratio of comments to source code line (like 1.5 comment lines per 1 line of code). If someone tries to stick to such ratio, it would be a waste of time in some cases and insufficient in the others. The bottom line is that if code is trying to do something "clever" (tricky algortihm or complex logic flow) then be generous with your comments. Otherwise, you can get away with just a few comments and save yourself some time. If you are just starting to program, you won't go wrong putting more comments in. Otherwise, let your intuition and experience be your guide.

One final observation is that I find comments at the beginning of source file most helpful. A paragraph or two describing what a heck is going on can go a long way to helping me understand some key ideas without having to skim through the entire file.

You're both wrong. (1)

ph4s3 (634087) | more than 9 years ago | (#12354635)

Software is the only designed/engineered product that doesn't have accompanying documentation such as a schematic, blueprints, etc.

Comments would be suruflous if there were a design document that accompanied the final product. By looking at the code one would be able to determine where they are, similar to standing in a house and knowing where in the blueprint you are based on your surroundings. Comments are not sufficient because they can't communicate the context of your position within the code; rather, you must read the comments to see what the code is doing, but you must examine the entire routine(s) to determine the methodology used to solve the particular problem(s). Until software has a blueprint-like document that goes with the code and the delivered binary/executable, comments will be necessary but woefully inadequate.

My opinion (1)

karvind (833059) | more than 9 years ago | (#12354638)

Answer to this question may differ from programmer to programmer. But I strongly feel, it helps in Debugging, Reverse Engineering, Re-engineering, Testing and giving the code a neat look. Moreover, it's a step towards standardization of coding methodology.

An interesting article on ZDNet on Documentation is good, but source code is better [zdnet.com]

Good documentation practice [linux.com] from Linux.com.

Load More Comments
Slashdot Login

Need an Account?

Forgot your password?