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!

What is Well-Commented Code?

Cliff posted more than 12 years ago | from the inlined-internal-documentation dept.

Programming 826

WannaBeGeekGirl queries: "What exactly is well-commented code anyway? Can anyone suggest resources with insight into writing better comments and making code more readable? After about six years in the software development industry I've seen my share of other people's code. I seem to spend a lot of time wishing the code had better (sometimes _any_) comments. The comments can be frustrating to me for different reasons: too vague, too specific, incoherent, pointing out the obvious while leaving the non-obvious to my imagination, or just plain incorrect. Poorly or mysteriously named variables and methods can be just as confusing. In a perfect world everyone would follow some sort of coding standards, and hopefully those standards would enforce useful comments. Until then, any suggestions for what you, as a programmer, consider to be good/useful/practical comments? Any suggestions for what to avoid? Also, I usually work with C++ so any resources/comments specific to that language would be too."

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

first post (-1, Offtopic)

Anonymous Coward | more than 12 years ago | (#3548802)

I can't believe I'm actually doing this. :-)

Re:first post (-1, Offtopic)

Anonymous Coward | more than 12 years ago | (#3548860)

Well, you did and you're an Anonymous Turd sucker, so FUCK YOU!

reply (-1, Offtopic)

fixed (578902) | more than 12 years ago | (#3548805)

it looks like I ::MAY:: have gotten the first post... doubt it though

Variable Names (1, Funny)

ludey (302445) | more than 12 years ago | (#3548807)

I sometimes get, uhh..."creative", before I program. End up with variable names like "$iHateThisProgram" and "$godFinWorkAlready"

Anyone else experience this phenomenon?

Re:Variable Names (2, Insightful)

alpha1125 (54938) | more than 12 years ago | (#3548866)

My variable names usually are forced into be changed after a code review by my peers...

They don't have that funny bone, when the code is going to be in production software, and maintance by others.

It's a professional image thing...

Re:Variable Names (4, Insightful)

gazbo (517111) | more than 12 years ago | (#3548870)

I experience code from others who have this problem, and frankly it pisses me off. Not meaning to flame you, but what seems creative and amusing at the time stays in the source, and becomes stupid and annoying later.

The same goes for 'amusing' comments in the code, or CVS logs.

For your sake in the future, and your coworkers' sake now, please stop it.

PS. Did I mention how fucking annoying it is?

Re:Variable Names (-1, Troll)

Anonymous Coward | more than 12 years ago | (#3548900)

I'll bet you pencils are all sharpened to the same length and neatly lined up in a row across your desk, too.

Re:Variable Names (-1, Troll)

Anonymous Coward | more than 12 years ago | (#3548875)

Anyone else experience this phenomenon?

Ohhhhh... Yeah! Just after I pull the ol' "slip stick" out my ass!

Re:Variable Names (0)

NWT (540003) | more than 12 years ago | (#3548923)

Not quite... when I program, i just take the names that come to my mind. These are often $foo, $muh or just plain $data, sometimes $raw_data.

But i think a clear code-structure is more important than variable names or detailed comments.

Re:Variable Names (5, Insightful)

emag (4640) | more than 12 years ago | (#3548937)

On one of the last projects I worked on, the specs we received from the customer were horrendous. Actually, it wasn't the customer themselves who had done the specs, but another contracting firm. Spending 5 months on the project, and finding repeated errors in the "data maps" (it was apparently too bloody difficult for us to be supplied with a schema for the DBs we were supposed to be accessing and updating), I'd finally had enough.

Querying the DBs directly showed that the data maps were works of pure fantasy in several spots, or would lead to outright data loss if followed precisely. In a fit of pure...creativity...I ended up setting a "$workAroundFuckups" variable, and in the sections where it was needed, had a false evaluation do precisely what thee datamaps said, which would corrupt data. If the variable was true (ie, non-zero), it would work correctly, which meant ignoring the data maps and doing what was needed to have the data be entered correctly.

I ended up getting moved to another customer (due to the limited resources *we* had, not because of my creativity), so I don't know if the remaining folks on the project removed it after I left. When I added it, I explained to them precisely why I'd added it, and since they'd had similar experiences with what we were given to work with, were behind me 100%.

This wasn't even the *only* part of the project which was FUBARed, but it was unfortunately what I spent many a 15+ hour day dealing with, so I was rather familiar with it. Had I access to the server that *read* the data and used it, I probably would have just gone in and redesigned everything "for free", just to avoid having to deal with such a horrible layout.

This is also the client where, after a few months of an irksomely out of sync clock (off by 12 hours...made figuring out when something happened a bit of a PITA), I finally went in and set the damned clock to the proper time. Not surprisingly, the same folks who made that wonderful novel for us were the ones admining the dev server we were working on. AFAIK, no one ever noticed that the time suddenly became "correct" either.

Code Complete (5, Informative)

kimba (12893) | more than 12 years ago | (#3548808)

I can absolutely recommend a book called Code Complete [amazon.com] . Yes, it is published by Microsoft, but it is an invaluable language-agnostic guide to writing software that includes heavy doses of common sense regarding commenting, coding styles etc.

Re:Code Complete (0)

Anonymous Coward | more than 12 years ago | (#3548868)

I agree totally. Excellent book. It even has a list of how you explain to your boss why you should put in some effort in design.

It also teaches you how to write selfdocumenting code and when it's necessary to explain things further in comments.

Buy it today.

Re:Code Complete (5, Insightful)

NewtonsLaw (409638) | more than 12 years ago | (#3548893)

I can absolutely recommend a book called Code Complete [amazon.com]. Yes, it is published by Microsoft

Yes, that's on my bookshelf -- but, given the fact that they go to great lengths to point out the importance of checking for buffer over/under-runs and fencepost errors, one can't help wondering if (in the wake of all those critical bugs in IE/Outlook/IIS) any of Microsoft's own programmers have read it.

More "do as we say, not as we do" from Microsoft?

Re:Code Complete - Something good from Seattle!! (1)

Dillan (547965) | more than 12 years ago | (#3548897)

I'd second this, I started coding in FORTRAN/RAMBOTRAN many years ago and now use c/c++/php. The book is a very good read with some good anecdotes and worked examples. The best bit is that it is fairly language independent.

Re:Code Complete (2)

ZanshinWedge (193324) | more than 12 years ago | (#3548924)

I agree completely, it should be on every programmer's bookshelf. You can hardly call yourself a professional software engineer if you have not read this book.

Re:Code Complete (3, Funny)

jsse (254124) | more than 12 years ago | (#3548953)

Yes, it is published by Microsoft

*Abruptly stops the finger from clicking the link*

Make the variable names mean something! (2)

dweezle (200818) | more than 12 years ago | (#3548814)

I Have to scan through code regularily and the biggest problem is the variable names. I realize that they must mean something to the coder but to us maintainers they're most times akin to Sanskrit. Function(method) comments are nice too.

Describe before you apply (3, Funny)

inflex (123318) | more than 12 years ago | (#3548816)

I like to see comments where the function of the next code block is well described in a continuous comment block. Additionally, any further specific comments can be placed at the end, or on top of the lines in question. It's simple enough, and permits comment/documenting-scrapers to produce some potentially useful documentation.


ie,
// Foo():infinite loop
// We attempt to complete an infinite loop
// here as quickly as possible, in order to
// remain true to Linus's statements of
// being able to do them faster with linux.
while (1) {
... // Oooh, this is a fancy line, watch out for it doing nothing.
}

Re:Describe before you apply (2, Interesting)

ranulf (182665) | more than 12 years ago | (#3548888)

The problem with this is that
while (1) {...}
or more commonly
for (;;) {...}
is a well known construct for infinite loop. If you turn such a simple construct into six lines of source, then I dread to think how much commenting you'll use when you actually get down to solving the problem in hand.

for (;;) { // infinite loop
is far better - it reminds people what you're doing and if someone sees your code and doesn't understand that construct then they know what it does from the comment and they can go and find out how it works and learn it for next time.

While you're at it, you should probably think about hiring real programmers who know basic constructs in their chosen language...

I better choose my examples (1)

inflex (123318) | more than 12 years ago | (#3548914)

Sheesh, so much for examples... the code was not intended of course to be specific... rather it was to act as glue to the comments.

Now, where's my dictionary.

Multiple passes to your code (4, Insightful)

fractaltiger (110681) | more than 12 years ago | (#3548889)

are the best way to comment it all.

One day you're commenting on what variables do, the next you try to explain functions, etc.

I just switched to Java from C++ and neatness is the most important thing I've acquired, not in code per se, but in variable naming. I've gotten used to doingThisWithVariableNames and DoingThisWithClassNames, while keeping THE_CONSTANTS capitalized. Ok, this isn't comments? But you'll be surprised at how much better it is to browse a new language like Java and see the norms of style in it, because old languages use too many confusing double_StandardslikeWritingThis_way.

Comments go at the top of a page, with the coder's name and date, as well as a small bug report and if you can, a brief function list for those without a visual IDE like JBuilder. You then put a like with PRE: and POST conditions in your code and try to keep one liner comments to a min.

I learned to comment the end of if structures and function blocks to make the code easier to follow... just add " } //end if" or something.

Comments should be a paragraph long so that they make some sense. And comments, since they look different from the code sections, should be embelished with ===============, stars, and some
nice spacing and vertical bars.

Good comments to me mean good-looking comments, even if they don't have that much substance. Just my 2 cents. They're better than no comments at all.

Re:Multiple passes to your code (1)

inflex (123318) | more than 12 years ago | (#3548926)

"I learned to comment the end of if structures and function blocks to make the code easier to follow... just add " } //end if" or something"

I agree, often that's a really good way of saving a few moments flicking up/down trying to determine which 'terminator' belongs to which block, things like } //end of "while (foobar...)" enhance it more.

Microsoft Press (2)

ObviousGuy (578567) | more than 12 years ago | (#3548819)

Code Complete by Steve McConnell

Writing Solid Code by Steve Maguire

Comments are evil. (0, Flamebait)

slumpie (127664) | more than 12 years ago | (#3548820)

The best comment is the code.

Re: Comments are evil. (2, Funny)

dorward (129628) | more than 12 years ago | (#3548864)

The best comment is the code.

Unless the code is Perl ;)

Per project (2, Insightful)

mnordstr (472213) | more than 12 years ago | (#3548821)

I guess the only real solution is to give a specific coding standard for every project. Before you begin coding, make up a standard that every developer has to follow, for comments, code layout, etc.

A good standard for C++:
http://www.possibility.com/Cpp/CppCodingStandard.h tml [possibility.com]

Re:Per project (0)

Anonymous Coward | more than 12 years ago | (#3548892)

I think it's more important to learn developers how to write 'elegant code', not to write a code standard for every project. The standard will probably change and it gives the developer more things to worry about.

It's better to give them a quick reference on how to write and why it's good with 'elegant' code.

+ a IDE with refactoring is gold worth. (It's hard to come up with good variable and function names at all times.)

Timeless Prof D.Knuth says it best... (2, Informative)

gmarceau (119282) | more than 12 years ago | (#3548824)

The practitioner of literate programming [literateprogramming.com] can be regarded as an essayist, whose main concern is with exposition and excellence of style. Such an author, with thesaurus in hand, chooses the names of variables carefully and explains what each variable means. He or she strives for a program that is comprehensible because its concepts have been introduced in an order that is best for human understanding, using a mixture of formal and informal methods that reinforce each other. Donald Knuth. "Literate Programming (1984)" in Literate Programming. CSLI, 1992, pg. 99.

Good Commented Code (1)

guinan (191856) | more than 12 years ago | (#3548826)

While I'm personally of the opinion that the level of comments that's acceptable depends a lot on the purpose of the application and the number of people working on the project, a friend of mine learned a very good ( if slightly anal retentive ) coding style from reading angband [phial.com] source code.

Maybe not for everyone, but you may want to try it.

Just tell me what a section of code is for. (2)

foniksonik (573572) | more than 12 years ago | (#3548827)

I only work with Perl. When I'm looking at someone else's code all I ask is that they outline the basic function of a particular section of code so when I need to change/enhance/debug something I can find the right area to start looking as quickly as possible.

I've never had to deal with 'obfuscated' code so I don't know about onscure variables, etc.. or how much more complicating they could be to my task.

Just point me in the right direction. Anything else is going to be too much or too little... and if I don't already know what the code is supposed to be doing I probably should be talking to someone who does before I sit down to work on the code itself.

Obviously reverse engineering of software is a whole different beast.

Re:Just tell me what a section of code is for. (2, Funny)

inflex (123318) | more than 12 years ago | (#3548837)

"I've never had to deal with 'obfuscated' code so I don't know about onscure variables, etc"

I thought Perl was the most efficient self-obfusicating code ever.

Good Comments (4, Insightful)

jamieo (22197) | more than 12 years ago | (#3548828)

Good code comments should describe the intention of the code. Write them *before* you write the code in a function/method to describe it's purpose. This will make you think exactly what you want it to do, and will allow for others to find/fix bugs easier when the implementation doesn't meet the intention.

I then write inline comments in the code describing it's flow. It's only then do I actually write the code.

Comments at file/class level should describe what it does and is used for. It should also describe how it fits in with the big picture of it's packages and the classes around it - give a reader some architectual scope to what they're looking at.

Get into a habit, even for trivial functions/methods and you'll soon not realized you're doing it.

Some people say code shouldn't need commenting, and the code itself should be enough. In a perfect world of no bugs and only populated by wizard programmers, this is fine, but not in the world I live in. You write some code and someone else (maybe yourself) will have to debug it at some point - maybe 3-4 years down the line. Even with a "neat" language like Java, working out how things work is much more time consuming without comments.

Re:Good Comments (1)

reinterpret_cast (534281) | more than 12 years ago | (#3548910)

We have been using Doxygen at work for more than one year and it's great, nice HTML etc. but I find the problem not being in the way you document the code: the most important is to have people to realize that documentation is necessary both for them as well as future developers. Working cooperatively is not just to use CVS, is also to provide to your fellow developers means to understand what you write.

my work (2)

drDugan (219551) | more than 12 years ago | (#3548830)

I use doxygen++ for C++; it's great

about 1/4 of my lines are comments -- most all of which are incorporated into doxygen descriptions -- and the rest only appear in the sourse listings

see http://www.doxygen.org/

Re:my work (2)

David Kennedy (128669) | more than 12 years ago | (#3548915)

Agreed - the best form of commenting is peer-reviewed
JavaDoc or Doxygen. I've used both and used to love
Doxygen, it's superbly flexible and easy to use.

It helps to gather up the real things people should be commenting; pre-conditions, post-conditions etc
and not "Infinite loop".

Plus it looks nice presenting your docs on a
website as part of the nightly build, or printed
out as a (huge) pdf book. All for no hassle.

Re:my work (1)

magi (91730) | more than 12 years ago | (#3548938)

I like the reversed documentation order that Doxygen supports. For example:

int IODevice::readBlock (char* data, /**< Data buffer */
uint maxlen /**< Length of the buffer. */ )
{

Use plenty of expletives (5, Funny)

oingoboingo (179159) | more than 12 years ago | (#3548831)

Well commented code should definitely contain a liberal smattering of four-letter expletives, eg:


// no fucking idea how this works
obj.doMagic();


or...


//bet those fucking lazy cunts in the QA team don't pick this up
fileSystem.delete();


When your code is released as open source and becomes famous, people can amuse themselves by searching through the source code to find all the hidden expletives, sort of like easter eggs. If you work for a commercial organisation, you can sit back and enjoy the panic as the QA and release teams sweat it out trying to track down every last filthy utterance before shipping to a fucker...errr..customer.

Re:Use plenty of expletives (2)

laserjet (170008) | more than 12 years ago | (#3548863)

My favorite is:

//fucking piss drunk... not sure why this works, but will fix later.

Programming Style (0)

Anonymous Coward | more than 12 years ago | (#3548832)

My style mini-guide [exorsus.net]

Essential items of any source code:

* Easily readable function and variable names
* Functional comments, expressing intent
* Large indent, making blocks obvious
Opening statement and closing brace of a block are on the same column for fast correlation.
* Consistant naming, all lower-case, _ for space.

Some of these are contentious at the moment, see the link above for further details on why I believe in these. Regarding comments strictly, as I said it is commenting *intent* that is important. Commenting function is pointless, if you need to comment function your CODE is broken. The commenting of function is one of the leading cause of "lies" within code, that is, some aspect oor another that leads a reading programmer to assume to code operates in a manner which it does not. Examples of this are incorrect comments, badly named variables, and to a lesser extent badly scoped variables.

So, commenting is not just a positive, it can cost you more than no comment at all if it is incorrect, sending the maintenance coder on a wild goose-chase through perfectly fine code looking for a bug that is overshadowed by an incorrect comment.

Suck my dick (-1, Offtopic)

Anonymous Coward | more than 12 years ago | (#3548834)

And the truth shall be revealed. That is how you become a REAL Geek Girl.

No, Call it what it is (-1, Offtopic)

Anonymous Coward | more than 12 years ago | (#3548853)

Knob bobbin'. No Geek Girl wannabe is worth a fart if she can't get it right.

Doxygen, etc (5, Informative)

Stary (151493) | more than 12 years ago | (#3548836)

Tools like javadoc, or maybe better in your case doxygen [stack.nl] can really help when it comes to commenting code... the idea is pretty much that you place a documentation comment before each function, or class, and so on, which usually makes the entire thing much easier. Having done that, I've found that only a few more non-obvious parts have to be commented within the actual functions.

How to write unmaintainable code (1)

xmda (43558) | more than 12 years ago | (#3548838)

I guess most of you have seen this page on how to writing unmaintainable code before, but I'll post the link anyways:

click me [mindprod.com]

Rule of thumb (1)

Overcoat (522810) | more than 12 years ago | (#3548839)

Isn't the rule of thumb" "don't just explain what a given block of code does, instead explain why you put that block of code in there"?

A little simplistic, but a good start, IMHO

Re:Rule of thumb (1)

caca_phony (465655) | more than 12 years ago | (#3548891)

Isn't the rule of thumb" "don't just explain what a given block of code does, instead explain why you put that block of code in there"?

As far as I am concerned, apart from exceptional circumstances, the code should make clear what it does (well designed data structures help alot with this). Explaining what well written code does in anything but assembler should be redundant to anyone but a novice reader of code. Why is another matter, why it is being done should be explained in your comments as clearly and concisely as possible.

Re:Rule of thumb (1)

ObviousGuy (578567) | more than 12 years ago | (#3548918)

Those readers of your code will be novices at some point in their career. Comment and code as if all your readers were novices.

Simple rule of thumb (1)

nagora (177841) | more than 12 years ago | (#3548840)

The documentation should be longer than the code. If that's enforced then most people can hardly help but actually explain what's going on.

TWW

Re:Simple rule of thumb (0)

Anonymous Coward | more than 12 years ago | (#3548945)

This is stupid. Not only do you have to maintain the code. You also must maintain and keep the long documentation up to date. Write code that is easy to understand and comment about wierd / unusual sections (like bugfix code).

Re:Simple rule of thumb (0)

your_name (248483) | more than 12 years ago | (#3548959)

That's not a good idea at all. That encourages rambling pointless text, not quick precise explanations. Lose your rule of thumb.

The Comment Mantra (0)

rob-fu (564277) | more than 12 years ago | (#3548841)

Taken from a Slashdot reader:

Real programmers don't comment. It was hard to write. It should be hard to read.

Overload whitespace to something meaningful! (1)

Lt.Hawkins (17467) | more than 12 years ago | (#3548843)

Re:Overload whitespace to something meaningful! (1)

ranulf (182665) | more than 12 years ago | (#3548928)

After the ridiculous interview a few years ago where Stroustrup claimed that C++ was a practical joke designed to keep software engineers, he really has made things a bit too obviously stupid with this one. Having an important block of code reduced to two characters that you can't even type (without using a tool to insert special characters) seems frankly ridiculous.

The double backslash - everything before this is a comment - is particularly amusing.

In fact, I even started looking for a date of April 1 whilst reading this document.

Re:Overload whitespace to something meaningful! (0)

Anonymous Coward | more than 12 years ago | (#3548932)

I hope that this paper was written on April 1st

I now understand why C++ is such a mess.

a set of standards is the key (1)

potcrackpot (245556) | more than 12 years ago | (#3548844)

The secret here (I believe), is that if you are involved in a group effort where you have to read (and correct) other people's code, you have to have a two-fold practice.

  • Develop a set of rules (coding standards), setting out not only comment style but variable naming conventions (e.g. capitals for constants, mixed for locals etc.). Ban things which make the source code several characters shorter but otherwise have no benefit. Make the rules as rigid and as specific as possible, and update them regularly. Then enforce them.
  • Develop a development cycle - design, code, review, test. The only one that really needs expanding on here is review - ensure that the code meets the coding standards and that it should work. Apart from appearance and conformance with the design, check for things like tight-looping, etc. Don't bother compiling and testing it (the coder should have made sure it compiles and done preliminary testing to make sure it doesn't crash straight away). Just eyeball it. DO NOT BE AFRAID TO BE AS PEDANTIC AS HELL. Whatever grief you'll be giving them they'll give back - as you should review each other's code in the same team (this also makes life easier when it comes to you, the reviewer, fixing a bug in the code at a later date).

With 50 people all writing code for the same project going through this process, you shouldn't be able to tell who wrote which bit.

The disadvantages to this are that it makes coding a bit robot-like - but hell, all the work was done is design anyway. People might also say that typing comments takes too long - but so does having to work out what the code does every time you look at it - instead of it staring you in the face. If this isn't what you want to hear, then try simply having a block comment for every code block, and a header at the top of every source code file. You should this way have as many lines of comments as lines of actual code. This is not, despite what others may say, a bad thing.

K&P's "Practice of programming" (1, Interesting)

Anonymous Coward | more than 12 years ago | (#3548845)

This book is a must-read on programming style. It also contains a perfect chapter on how to comment the code clearly.

Coding Standards (1)

benjymous (69893) | more than 12 years ago | (#3548846)

Company wide coding standards are implemented where I work, and whilst many people see them as an affront (i.e. "I'm already a good programmer - why should someone else tell me how to program) it does mean that code from other people is usually pretty easy to understand.

Here are some of the key points in ours:

function headers:
put a description of the function, and what its inputs/outputs are/do, the original author and the date of creation. Anyone who modifies this function in the future (beyond very basic changes) should add their name and the current date, plus a quick description of what they changed

variable naming:
adopt a standardised and logical hungarian notation for the variables, and try to avoid abbreviating when the full word would do. "nCount" is far more descriptive than "cnt"

Other things, such as always including { and } in C, and putting them alone on their own line makes the code much easier to read (though longer, but I'd rather read long meaningful code to compact confusing code) and putting plenty of bracketing in equations

Over commenting (0)

lpwuk (303587) | more than 12 years ago | (#3548848)

When I was at Uni, I got marked down in a class once for over commenting my code!!!

I include a variable definition block at the top of each function describing what each variable was for.

Each function got its own description and then comments were in the code when I was say, performing some test.

Still, that is University for you :-)

commenting code (1)

caca_phony (465655) | more than 12 years ago | (#3548851)

I was most impressed by the advice Rob Pike gives on commenting code. If I remember correctly, his main points are: write code so that it is uncluttered and acts as it's own comment, never paraphrase the code itself, but rather explain metastructures and relations (otherwise you are more likely to have outdated comments that were redundant in the first place; a line is more likely to change than the overal logic). Keep both comments and code concise and clear. And call it complex_multi_word_variable, not ComplexMultiWordVariable, for readability's sake.

CRC please... (1)

shic (309152) | more than 12 years ago | (#3548852)

My vote is that everyone should use a CRC (Class Responsibility and Collaboration) style (wherever sensible). I want to know why a class exists and where it is to be used and what is its purpose - down to the level of detail of behaviours of individual methods. Thereafter I prefer to see concise and compact code and shy away from comments reading as if a chatty soliloquy (which often bears little or no correlation to the code - especially after it has been "maintained" by a few people!)

Coding standards, to me however, seem to be quite a red herring... all code should be correct, coherent, compact and with a similarly crystal-clear specification. Most "coding standards" I've encountered have concentrated on fine-grained stylistic issues while ignoring the wider goal of concise clarity.

Make each comment count. (0)

Anonymous Coward | more than 12 years ago | (#3548854)

a bad comment would be something like

for(i=0; i

Obviously anyone who understands the language itself understands what the standard statements do, and anyone who doesn't understand the language probably doesn't have much reason to follow the program flow line by line.

Good comments are a level or two more abstract, and cover the medium-to-big picture of what functions and chunks of code are there to accomplish. Comment any *unusual* pieces of code, and any code that is doing something tricky, "clever", or simply less than obvious. Use code as a sort of "caulk" to fill in the holes of understanding in your code. Don't narrate the entire program line by line, but also don't hesitate to comment where the code is unclear.

If the code is consistently unclear, it may be an indication that your code should be more readable overall.

Re:Make each comment count. (0)

Anonymous Coward | more than 12 years ago | (#3548862)

Whoops.

Should've previewed. "Plain Old Text" apparently still snarfs "<" signs.

The "bad comment" line was just an example of a perfectly clear line of code being subsequently "narrated"; ignore it, since it didn't come out right.

Different parts of the brain (2, Informative)

heretic108 (454817) | more than 12 years ago | (#3548856)

I also have seen my share of other people's code.
Quality of comments varies.
I've seen code from the 'hardcore hacker', who believes that the statements themselves suffice as comments - 'the code is intuitively obvious, and it comments itself'.
I've also seen code from complete lamers, who dilute the code terribly with irrelevant shit:

i++; // increment i

Over the years, I've noticed that composition of code, and commenting/documentation of code, tend to draw on two different parts of the brain.
Often, I find myself in a 'zone', where the code flows freely, and where commenting code feels like a total distraction.
Other times - for instance, when I'm hunting an elusive bug, I find a different part of the brain kicking in - and at that stage, I find it easier, even pleasurable, to add meaningful comments, to change indenting, variable names etc, as if I'm narrating the code to someone else.
I guess it's a matter of balance, and using the right mental faculties at the right time.
A good rule of thumb is to imagine that someone else is sitting beside you, someone less acquainted with the task than yourself (eg a non-technical manager). Imagine you're explaining to him/her how the code works, and put these explanations in the code as succinct yet clear comments. Imagine this person asking you, 'what's that variable'. Don't be afraid of global search'n'replace of identifier names across all the applicable files. And imagine this person sometimes getting up and leaving you in peace, so you can have those precious moments to hack to your heart's content.
In conclusion, I feel that much of a person's personality can be read from one's code. Is someone fundamentally easygoing and helpful, and caring about others? Or is someone a complete egotist, emotionally shut down almost to the point of autism? In my mind, the ability of code to communicate its intent and methods to other programmers is almost as important as the code successfully performing its task, since its communicability directly affects the ability and interest of others in working on it, and thus its openness to manpower leverage.

Re:Different parts of the brain (1)

inflex (123318) | more than 12 years ago | (#3548869)

"I find a different part of the brain kicking in - and at that stage, I find it easier, even pleasurable, to add meaningful comments, to change indenting, variable names etc, as if I'm narrating the code to someone else.
I guess it's a matter of balance, and using the right mental faculties at the right time."


Hail! Yes indeed, in chasing a bug I often fix it without noticing simply by doing as you have mentioned, going through, cleaning up, as though doing a multipass on source code makes it clearer like an interlaced JPEG :-)

Re:Different parts of the brain (0)

Anonymous Coward | more than 12 years ago | (#3548886)

Your 'increment i' example seems a bit simple, but let me give you something to think about.

Sometimes you're not quite sure how something is going to work, so you have to lay it down as a series of steps in comments first.

/* open the device */
/* flip through the table looking for foos */
/* track how many we got */
/* shut it down */

Then you come back and stick the code to do all that junk in between the comments. A year later, you may cringe for documenting something so obvious, but the fact is, you HAD to have it to get started.

People who bitch about comments being too obvious probably don't realize that they may have been used as scaffolding to get the function built.

Now, if you have lusers who rabidily comment everything after the fact using that kind of braindead obvious notation, you have a genuine problem. The trick is telling one from the other.

It's been a long time but.. (5, Interesting)

NewtonsLaw (409638) | more than 12 years ago | (#3548857)

It's been quite a while since I wrote any significant amount of code but after spending far too many years cutting code too early in the development process I eventually woke up to the fact that coding is the *last* thing you do (apart from testing and debugging that is).

First-up you need a good spec -- and the spec should include the user-interface details to the extent that you could actually write the user-manual from that spec.

Indeed -- if you can't write the user-manual from the spec then the spec is incomplete.

From the spec the programmer should develop the structure of the code in another document.

That structure document is repeatedly refined in a top-down process until you (eventually) reach a point where you're actually cutting code.

I was always surprised just how much easier it was when the code was written as the lowest level of the structure documentation.

Not only could you comment out the program structure document so that the compiler would ignore it -- but you ended up with absolutely accurate and comprehensive documentation built into that source.

Project managers love this technique (and when I was in a project management role I demanded it of my team) -- it ensures that technical and end-user documentation are no longer the bits that get left until last and thus are either very shoddily thrown together or, if the project goes really over-budget, not produced at all.

Of course, as we all know, there's a huge amount of temptation to just leap into coding at the earliest possible stage and leave the documentation until later -- because some stupid managers use number of code-lines completed as a metric of project performance -- duh!

If you're smart and use good tools you can selectively collapse and expand the in-source documentation so that when you're trying to get familiar with a module that someone else has written, you can descend down the structure tree one level at a time without the meaning being diluted by stuff that is at a lower level.

Unlike the days of interpreted BASIC, there's very little overhead involved in integrating documentation and code these days -- so there's no excuse not to do it.

If required, the documentation can be automatically extracted from the source -- but by keeping the master copy in the code it becomes easier to ensure synchronization as changes and updates are made during the lifecycle of the project.

UML and RUP (1)

mikolajl (309623) | more than 12 years ago | (#3548861)

For big projects (and only big projects) using the Unified Modelling Language [omg.org] and especially the Rational Unified Process [rational.com] is very useful.

Rational has quite a few tools [rational.com] which (when used correctly) allow to trace what class is responsible for which business case.

Good coding method (1)

dybdahl (80720) | more than 12 years ago | (#3548867)

Having done coding and commenting for more than 20 years, the most successful I've found is this one:

Group several lines of code and comment them together with one or more lines of comments before the code. Example:

// This is an example of how to
// comment in an easy way
function doSomething (String s) {
// Initialize for the loop
int i=0;
int j=0;

// Set all characters in
// parameter s to space
while (condition) {
s[i] = " ";
i++;
}
}

Commenting standards (0)

Anonymous Coward | more than 12 years ago | (#3548871)



The coding team I work with have some standards that the analysts and other code reviewers try to stick with.

At the top of each 'significant' method, we whack a comment block such as this:

Name :
Description :
Date :
Pre :
Post :
Input Params :
Output Params :
Returns :

( and obviously fill it out ). One beauty of this is the description. If you can't describe your unction in a line or two, then your function probably needs to be broken down a bit further. It makes it a bit easier to follow the code if there's a nice header block to describe each function.

A naming standard for variables is good too.

We tend to follow a variant of the Hungarian notation ( ?? ) which has a single character to define scope ( local, module, global ) plus a character to denote variable type ( s for string, l for long, i for integer, o for object )

So, you get a variable like liCounter ( a locally declared integer for counting ) or goCounter ( a global Counter object )

Anyways, everyone has their own standard, the trick is, come up with a standard, and stick to it. Try to enforce ( encourage! ) the use of the standard. Even if no one else wants to, stick with it yourself, if you tend to maintain the code you write ( as opposed to someone else ) at least you'll be able to follow it !

Document the function's contract (5, Interesting)

IvyMike (178408) | more than 12 years ago | (#3548878)

Take a look at this function, and tell me if there's a bug:

void foo(void) {
int* x = 0;
int y = *x;
}

Easy, the bug's the SEGV, right? Take a look at the same function, this time with comments:

// Function: cause_segv
// Description: Causes a SEGV for testing purposes
void cause_segv(void) {
int* x = 0;
int y = *x;
}

The point? A bug is unwanted behaviorm, but that only makes sense if you've defined what the correct behavior is. My example is trivial, but often this is a real concern. Function "bar(int,int)" returns null whenever one of the arguments is negative--is that a bug or a feature? Your function has a goal in life, a contractual obligation to do something; make sure it's clear what that something is.

Note that if you choose good function and good variable names, a simple one or two line comment at the beginning is usually sufficient to document whe function's intended behavior.

I also find that an "assert()" or two on the arguments at the top of the function makes it clear what values the function accepts, and which one the function doesn't handle. It's an easy way to document the contractual obligations of the function.

Stuff not to put in comments is stuff that's easily devised from the code. Check this out:

// Function: square
// Inputs: int x
// Outputs: int
// Used by: pythagorean(int,int)
// Description: returns x squared
int square(int x) { return x*x; }

Did the "Inputs" or "Outputs" add any value? That information appears again, two lines below in the function definition, and it's guaranteed to be correct there (unlike the comment which will be out-of-date and wrong when we change "square" to work on longs). The "Used by" might have added some value, if it was correct, but as it turns out it's out of date, and 15 other functions now use "square". Any information better derived looking at the code should be left off. Any information which can be better found using "grep" or "find in files" should be left off. Any information that will probably be out of date at some point should be left off. Heck, in this situation even the description is probably extra verbiage, since it doesn't really help anyone. (I'd probably put it in out of habit anyway, though...so sue me:)

type* var is evil (1)

inflex (123318) | more than 12 years ago | (#3548904)

If we're in the mood to split hairs... then declaring variables as

type* var1;

is rather misleading in itself, ie: char* foo, bar;

Whilst most people can instantly tell that it's meant to be a pointer to char and a char, it might not always be obvious if the programmer wanted two pointers, or a pointer and a char.

Better to place the * with the variable name [imho ;)] ... char *foo, *bar;

Re:type* var is evil (1)

ObviousGuy (578567) | more than 12 years ago | (#3548913)

Mass variable declaration is evil.

If you need to declare things, break them out to their own lines. That makes it easy to add comments to each one when necessary.

char* foo; // This is our output buffer (we should have used a more descriptive name)
char bar; // Descriptive comment here

Re:type* var is evil (1)

silvaran (214334) | more than 12 years ago | (#3548943)

Believe it or not, I use Microsoft's notation to make pointers to strings. While they use stuff like LPSTR (ugly - long pointer [32-bit] to a string), I do a
typedef char* pstr;
and
typedef const char* pcstr;
That solves the problem of your multiple-declarations. I suppose a lot of that is left over from C, where you had to declare all your data at the top of the block, but code like this is relatively clear (assuming you know what pstr is):
pstr begin, end, other;
and avoids the * notation, especially in a dynamic array of strings:
pstr* some2darray = new pstr[12];
some2darray[0] = new char[100];
or whatever.

Re:type* var is evil (2)

Twylite (234238) | more than 12 years ago | (#3548952)

OTOH, char* foo is arguably more logical than char *foo. You are declaring foo as being of type "character pointer". You are not, in fact, declaring a char with a pointer to it named foo (you never declared the char, only the pointer), which is what is implied by your recommended form.

Braces (1)

Kwil (53679) | more than 12 years ago | (#3548929)

I'm curious, but why do people place the braces where they do, is there any stylistic reason beyond tradition?

For instance, the code above has the following:
void cause_segv(void) {
int* x = 0;
int y = *x;
}
sprintf("Did it work?");
Yet personally, I like code formatted in this style:
void cause_segv(void)
{ int* x = 0;
int y = *x;
}

sprintf("Did it work?");
I find that when you get a bunch of nested blocks it becomes easier to follow.

When I see an opening brace as the first character, it's a reminder of the start of a nested block and I know I can skip to the close brace if I don't need to go into that block, with the blank line helping to easily spot the closing brace.

Re:Braces (1)

ObviousGuy (578567) | more than 12 years ago | (#3548957)

Whichever way you choose, you eventually get used to it.

Personally, I change the bracing style depending upon the language.

C and C++ get the One True Style:

int foo(bar)
{
if (something)
{
// code
}
else
{
// more code
}
}

Perl gets the cuddled style:

sub foo {
if ($something) {
// code
} elsif {
// more code
}
}

Folding helps (1)

AlecC (512609) | more than 12 years ago | (#3548880)

I find that the use of a folding editor which demands fold comments (i.e. nopt JEDit style) very valuable. If you get used to folding up your code, then you are forced to put enough comments in the body to make it readable.

There should be Javadoc-style header commments on any function more than five lines long (and most shorter).

If you have both of those, you won't get much better for commenting.

Projects should have coding standards, and people ought to conform to them even if they don't personally agree with them. Code written to one standard and modified to another is worse than either. If you can get automated formatters, tune them to your house style then use them.

It is possible to be too verbose, but it is much easier to be too terse. Err on the side of verbosity.

Standardise abbreviations. Is "Length" given in full, abbreviated to "len" or to "ln"? Whichever you do, always do the same thing.

Examples.. (5, Funny)

popeyethesailor (325796) | more than 12 years ago | (#3548881)

# all of these will also get moved elsewhere

# this is the worst damned warning ever, so SHUT UP ALREADY!

# Keep your friends close but your enemies closer.
# Or ignore them, we don't care.

# You know, we do assume comments are linear -Brian
Refer here [slashcode.com] for further details:)

from /usr/src/linux/Documentation/CodingStyle (2, Informative)

mav[LAG] (31387) | more than 12 years ago | (#3548882)

comes this advice:

Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it's much better to
write the code so that the _working_ is obvious, and it's a waste of time to explain badly written code.

Generally, you want your comments to tell WHAT your code does, not HOW. Also, try to avoid putting comments inside a function body: if the
function is so complex that you need to separately comment parts of it, you should probably go back to chapter 4 for a while. You can make small comments to note or warn about something particularly clever (or ugly), but try to avoid excess. Instead, put the comments at the head
of the function, telling people what it does, and possibly WHY it does it.


PDL it is good no? (3, Interesting)

ZanshinWedge (193324) | more than 12 years ago | (#3548890)

Personally, I like documenting backwards. Start with the requirements, work to the architecture, then get into writing PDL (Program Design Language). Essentially, you write out as detailed instructions on what the routine does as you can, without getting to the nitty gritty. It describes the intent of the code, not the code itself. It morphs into excellent comments when you expand it out into full code, and it also has the nice little advantage that it's at a high enough level that it's applicable to multiple languages (if you should desire to switch).

Offtopc(-1) (1)

jgp (72888) | more than 12 years ago | (#3548894)

WannaBeGeek*Girl*? Girl? What marvelous creature is this you speak of as "Girl"?

Literate programming (1)

awol (98751) | more than 12 years ago | (#3548895)

The best commented code is literate programming code. There is no better.

style(9) (1)

RinkSpringer (518787) | more than 12 years ago | (#3548896)

You may want to check out FreeBSD's style(9) [freebsd.org] manual page. FreeBSD uses this in the kernel, and reading most kernel sources usually isn't a problem for me.

Be political: No comments! (0)

zloppy303 (411053) | more than 12 years ago | (#3548898)

Good code speaks for itself, so the best comment is a not written (ie. dead) one ;)

Russian Programmer (0)

serv0 (447278) | more than 12 years ago | (#3548902)

It all depends on the person's personaltity and such. Personally i comment code that has taken me a while to code or figure out. i figure if i can figure it out than others can, if not then i comment for my self and figure if others are smarted than they wont need my commments. /*/* This code explains the fundementals of my commenting process */ this is my explanation of my commenting */

Re:Russian Programmer (0)

serv0 (447278) | more than 12 years ago | (#3548908)

I jsut want to aplogize for my great speeling and my gooder english?

Linux and other things. (4, Insightful)

jon_c (100593) | more than 12 years ago | (#3548906)

Personally I think the linux kernel is very well documented, at least the scheduling part, which is what I've looked at. Linus has a style of inserting huge comment blocks that explain exactly what's going on, then he'll have a page of code that does it, with little or no comments.

A style suggested in Code Complete (I forget what they call it) is to write a method completely in pseudo code, make sure it's correct, then insert the actual programming code under each line of pseudo code. This technique, while clever I find leads to many useless comments like "loop through the employee records" and "increment the counter".

A good test to see if the comments are working is through a code review, people will very often not know what's going on, or point out confusing comments or code that needs a better explanation. Code Reviews really improves your idea of what good comments are and teaches you what works and what doesn't.

Reveal the intention (0)

Anonymous Coward | more than 12 years ago | (#3548912)

McConnell's "Code Complete" says it all. Or, at the least, it repeats everything worth knowing in the one place.

A comment is to reveal intention. The comment tells you what the programmer was trying to do in the code block that follows the comment.

People who say 'Don't comment, the code tells you everything you need to know" are, frankly, bozos. The problem with that line of thinking is that when there is a bug in the code you have no idea what was _meant_ to be there so that you can fix the code. As far as the 'code is truth' mentality goes, the bug is correct behaviour, because that's what the code said to do. I can only imagine these people have never worked on systems written by other people.

An alternative to this sort of intention revealing comment is to use very short methods that do one small specific thing with a good verbed intention revealing method name - the method names play the part of the comment. A lot of Smalltalk is written this way. My (personal) view is that methods which are _too_ small (getters and setters excepted) are just as bad as methods which are 9 pages long, but that's a different topic.

My Aikido site : aikido.org.au

Coding Style (1)

calzplace (253241) | more than 12 years ago | (#3548919)

I'm a new C++ programmer, so I havn't had the experience of reading a *lot* of bad code, but from a few of the 'packages' I've seen out there I have a bit of an insight.

I personally think that following a specific standard of making the code itself readable and neat looking is required. Don't enclose huge statements using parens ( ) for a majority of the logic. This isn't a 1-liner contest -- its all about making the code more readable, using the appropriate amount of lines to get your point across -- both to the compiler AND your fellow programmers.

I think commenting is also very necessary, but can be way overdone. Don't comment the use of every for() loop, unless it appears complex enough to require an explanation. Comment on top of every function, even if just a little explanation, or personal thoughts like /* This execution flow is functional, but not very elegant -- consider revising in the future */
Maybe a good standard would be to comment on top of a function like the C library man pages?

Just a few thoughts. Perhaps a few programmers out there might want to go back to school and get a second influence, or perhaps a little slap on the wrist. :)

Inline Documetation and Automated Tools (1)

twoshortplanks (124523) | more than 12 years ago | (#3548920)

I don't need to add that many comments to my code (though I still do - probably a ration of 3:1 code:comments) as I use inline documentation. Perl's POD rocks. You just say what the code it meant to do before you do it.

Of course, I also use inline tests. Test::Inline [cpan.org] allows you to specify (and test) the expected behavior of your code. Now everyone knows that your funtion was suposed to do that and it's not just a bug!

Tools to check that you've commented everything rock too. Pod::Coverage [cpan.org] is an example of such a tool for Perl. It automatically checks if you've documented (inline documentation - pod - not just comments) each method.

Code Commenting? (1)

mthed (120041) | more than 12 years ago | (#3548921)

You mean, people actually do this after compsci 101? I thought it was just a cruel joke used to scare off new new coders.

--

Good commenting (3, Insightful)

RockyJSquirel (412960) | more than 12 years ago | (#3548925)

I wish I had time to go into more detail but I recommend:

1. Every class should have a clearly defined public interface and documentation of:
a) what the class is for and (if appropriate) why it was designed the way it was
b) how it works
c) how to use it
d) how to extend it (if there's any reason to do so)
e) it's lifetime / memory usage(if appropriate)
f) if it's tightly connected to any other classes or functions, that should be documented
g) how to make classes derived from it (if appropriate)

2. Every function should have a comment that says:
a) what it does
b) why (if there's any question)
c) what side effects it has (if any)
d) what side effects it depends on (if any)
e) if the functions is tightly bound to any parts of the program (it's not a context free sort of routine) then you should list where it's called from.
f) examples of how its used (if appropriate)
g) This one is important: describe the algorithm. It's important to keep this sort of comment up to date.

I'm not so enthusiastic about comments on individual lines of code. They seem less necessary to me than the other sorts of comments, especially if everything is well named.

I've been trying to get people at my latest company interested in code documentation, but I seem to have lost that battle. It's a shame. The only way to develop around here is to read every damn line of code, and that's unbelievably wasteful.

Rocky J. Squirrel

Read this book! (1, Interesting)

Joystickit (529613) | more than 12 years ago | (#3548930)

I am a big fan of The Practice of Programming by Brian W. Kernighan and Rob Pike. I picked mine up on Half.com for a decent price. They talk about not only good commenting, but good programatic structures and the like. One of their big things is to code in such a fashion that excessive comments aren't nessecary. Clean code needs less explanation than a dirty hack.

How long was the Six Day war? (0)

Anonymous Coward | more than 12 years ago | (#3548931)

Well, most of the comments I read in source code
are like the title of the message - Explaining
the obvious. The other comments are too lengthy
and diverge from the actual code during time...

The best is self documenting code. Good function
names and variables (easier said than done)

I once read about a policy in a company that
prohibited comments in source code. The code
reviews were strict and if the code was not
clear enough then it wouldn't be accepted. I
liked the idea and try to implement it in my
everyday programming.

Code organization, good function names, good
data types (classes) are much more important
and give much more information to the reader
of the code than any comment.

Don't write complex functions! (1)

alek202 (462912) | more than 12 years ago | (#3548934)

In order to keep a project simple, I follow a few guidelines:

- Avoid complex functions. If your function seems to be too complex, try to swap out some code into another function.

- Document the function's parameters and the values it return.

- Flame/Kill/Bitch me for that, but I tend to create some nice graphics which show the complete project with abstract components, so you get an impression of the whole project BEFORE YOU START CODING. This makes it easier to decide which objects/functions belong to which module. See http://www.monday-rec.com/timo/rs404/rs404.html (hope that works on every browser :)

Hope that helped a bit.

-Timo

Amazing grammer correctness! (0)

Anonymous Coward | more than 12 years ago | (#3548935)

"What exactly is well-commented code anyway?

Wow, this is like the first time I've seen some make the right anyway/anyways word choice at the end of the sentence. This just made my day. Now if people would start making the correct its/it's choice, I could die happy at the end of my life!

Screw comments (1)

firegate (134408) | more than 12 years ago | (#3548936)

Screw comments.. if they can't understand my code, they don't deserve to edit it.. It goes both ways.. Hail the spaghetti coders!

Why not what (2)

joss (1346) | more than 12 years ago | (#3548940)

It's real simple. If the reader can't tell what the code does from reading it, either it's written badly, or the reader is incompetent. In either case, comments won't help. If I see too many obvious comments, it's a clue that the author was clueless and I should probably just throw the code away because it will cause more trouble than it fixes.

When comments are useful is to fill in information that is obvious to the author but not obvious to anyone else reading the code. When the author wrote the class/function he knew why he was doing it, why the function was needed at all, this kind of information allows a new developer to get an overall understanding of the project much faster.

code comments (2, Insightful)

VonKruel (40638) | more than 12 years ago | (#3548944)

If the code is well structured, variables, classes, methods, etc. well-named and well-conceived, it will explain itself to a large degree, and won't require an English play-by-play of every friggin detail. Generally, it's a good idea to have high-level comments that say "this chunk of code does X", but lower-level comments are often a waste of time, and only serve to clutter the code. Having said that, sometimes code is unavoidably hairy, and you have to recognize cases where the code needs some lower-level explanation, and provide it. First, avoid complexity, failing that, manage it. Generally speaking, I think code comments serve the purpose of helping s/w people to develop a mental map of the code. Code should have as few comments as possible, but no fewer :-)

Tools matter (1)

wray (59341) | more than 12 years ago | (#3548956)

One thing that is hard to do is find a reasonable balance between commenting code, and bloating the file so that it is hard to find the code. Anyone else have this problem? For instance, sometimes even with syntax highlighting, getting through all that wordy commentary is like trudging through the haystack looking for the needle. Here is where tools matter.

First, use a good documentation program like doxygen or doc++ (C/C++) specific. Then a user can see the highlights of the code functionality in html, away from the code. This solves much of the overview type of code reading.

Second, use well-thought out function names and variable names and be consistent. This is often at the cost of space, but even if you are writing code just for yourself, I found it helps tremendously.

Third, use short, descriptive, comments to point out algorithm purpose, especially when it took you time to think through it. Try your best to not interrupt the flow of the code by putting comments on the end of the line.

Fourth, on my wish list is a tool that I have not seen. That would be some kind of comment compressor, like you do with expanding directories into trees on a GUI file manipulation program. Emacs programmers -- are you listening? :-)

Finally laying out code in a consistent manner (the right tool is indent here) really helps. Many styles have evolved because they provide visual feedback and cues about what you are seeing. Having and using a consistent style helps future mainters use those visual cues as they parse through your code. These cues can be more effective than comments because they are succinct.

Jutil.org documentation (1)

MarkoNo5 (139955) | more than 12 years ago | (#3548960)

Good documentation contains formal specifications. Although most "programmers" will not agree, formal specifications provide the best way to document your code. First of all, they tell the user exactly what the software should do or should not. Secondly, writing formal specifications forces you to think about what you're doing, and prevent most bugs and design errors, even before you write the actual code. Another advantage is that once the specification is written, the code and the test classes can be written independently, which should result in better tests because the specification says what a method should do, so you don't have to guess it.

On top of that, it should contain a description of what it (a class, package or whatever) should do, and class diagrams (a picture can say more than ....).

For an example, look at the org.jutil.java.collections package [sourceforge.net] of the Jutil.org [sourceforge.net] project. The math package doesn't contain formal specifications yet because not all functionality is present to write them (numerical mathematics ...).

If you want to write object-oriented software, read "Object Oriented Software Construction" by Bertrand Meyer, it's a must read.

Load More Comments
Slashdot Login

Need an Account?

Forgot your password?