do you comment your code?

Associate
Joined
18 Oct 2002
Posts
1,752
Location
Southern England
As the title really, do you comment your code and if so, do you do it while you're writing it or afterwards? how detailed are your comments and do you write them for your reference or so that others can understand the 5 nested for.. next loop you just created?

Personally, I comment as I go and write it so it explains what's going on to anyone who happens to go .. view/source :)
 
I usually copy and paste the pseudo code algorithm from my detailed design docs into the source code, comment tham out and then fill in the gaps with code

Either that or if I've done propper UML designs the source code generator will write all of my method headers for me when it generates the class / method stubs.

So YES always comment your code it's a good idea. I once had a lecturer who insisted that well written code didn't need comments as it should read like a book :eek:

HT
 
I always comment my code, especialy because of automatic java docs and so other people can understand it. With my assemmbly its the other way round, its so when I come back to it in a few months I dont have to work out whats going on again :)

happytechie said:
I once had a lecturer who insisted that well written code didn't need comments as it should read like a book :eek:

I find it hard to get a good balance between readability and efficiency, guess its just an engineering tradeoff.
 
Last edited:
Depends how complex it is. Straightforward stuff I won't comment, but complex pieces I will comment.

I've played around with some of the automatic comment programs out there - Zend Studio integrates with PHPDocumentor - but they're a bit OTT for my needs.
 
I comment functions with their purpose, paramaters, return type and a usage example using phpDoc, then find that that the rest of the code tends to be self-evident, particularly if you adhere to principles like having short methods and not using ridiculously terse/obfuscated language.

A lot of it comes down to method and variable names, too. I mean, if you see something like this:

Code:
string newFilename = @"C:\foo.txt";
File fileToCopy = new File(@"C:\bar.txt");

fileToCopy.Copy(newFilename);

Do you really need a comment to explain it?

Also, I'd like to add that old and out-of-date comments are a thousand times worse than not having comments at all.

Edit: Here's an example of phpDoc. IIRC, it's just a rip-off of JavaDoc for PHP, but I like it because it's machine readable and human readable at the same time:

Code:
/**
 * Fetches books from the database based on a given query.
 *
 * Example usage:
 * <code>
 * $books = nr_get_books('status=reading&orderby=started&order=asc&num=-1');
 * </code>
 * @param string $query Query string containing restrictions on what to fetch. Valid variables: $id, $num, $status, $orderby, $order
 * @return array Returns a numerically indexed array of book objects
 */
function nr_get_books( $query ) {
 
Last edited:
happytechie said:
I once had a lecturer who insisted that well written code didn't need comments as it should read like a book :eek:

What's wrong with that? It makes sense to try and write readable code that doesn't need every single bit of explaining with a comment. Feel free to write comments for sections of code which aren't particulary clear but remember that exessive commenting is both pointless and annoying.

Linus Torvalds said:
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.

Source: http://www.linuxhq.com/kernel/v1.3/53/Documentation/CodingStyle
 
The majority of my comments are in the header blocks for functions/pages/classes, following the PHPDoc syntax. I generally find that is more than enough for most classes and functions, meaning that inline comments are rarely needed. I agree that if a lot of inline comments are required, then there may be an issue with the code/code style. I write the header blocks before I start coding.

Within scripts, I section of blocks of code with clear headings as comments - signifying where input is being handled, template variables are being handled and so on. I usually do this before I start coding as a form of script template.
 
I find the commentator ( http://www.cenqua.com/commentator/ ) very usefull.

Seriously though, if it's code for a project I'm doing I rarely comment, but if I'm going to be releasing it, or if someone else is then I generally comment what methods, constructors, etc do, return and their parameters, and any complex areas, but if it's fairly obvious from the code then I won't.

Of course method names which make sense like doStuff() and returnSomeThings() always improve readability.

Col
 
Anyone involved in programming long enough eventually realises that they'll spend a great deal of their time doing "maintenance programming", and as such, you'll run across plenty of code that is poorly documented if at all. So if you are lucky enough to be developing some new code, or even modifying some existing code, don't think of yourself, think of your fellow coder who several years down the line, will have a project manager telling him to pick your code up and modify it to do something that it was never anticipated it would or could do :)
 
I only comment code in two situations:

1. Where it isn't well-documented elsewhere
2. Where it's not clear from just looking at it for 10 seconds what it does

I come across these situations relatively rarely. The comments I hate the most are 'TODO' ones all the time :p

arty
 
Comment most of my code. Methods are commented + inline comments when necessary. Of course ideally code should be readable and shouldn't need inline comments, but sometimes this isn't practical.

eg1 : I implemented a very mathematical algorithm (Scaled Conjugate gradient training), and it would make no sense without comments however well you programmed it.
eg2 : Sometimes it is necessary to do things in obscure ways for efficiency. For instance I wrote a program to solve a trickly puzzle game. Initially I wrote it nicely in a fully OO way, however it was too slow. I had to rewrite it using arrays and bit operations (XOR/OR etc) to make it fast enough. Such code isn't usually very clear.
 
I always tend to comment my code, as my memory is poor :p but it makes it much easier to come back to older programs i may have written and reuse them. I think it is even more important to comment your code if your are into object orientated programing so you can reuse class's.
 
not especially

shouldn't need to, in almost all circumstances. well-written code should pretty much state its purpose through meaningful method and variable names, and if it doesn't, you can probably refactor it so it does. which is easier to read?

...
CacheManager cacheManager = CacheManager.getInstance();
Set<XElement> elements = portfolio.getElements();
for(XElement element: elements) {
cacheManager.addAndSave(element);
}
...

or

...
// get reference to cache manager
CacheManager cm = CacheManager.getInstance();

// put elements into e
Set<XElement> e = portfolio.getElements();

// cycle through e, adding to cache
for(Xelement el: e) {
cm.add(el);
// save always saves the last added element
cm.save();
}
...

?

also, a major downside of comments is that they have to be maintained. In my last job, I was forever finding comments that were way way out of date compared to the code they commented on, the code had changed in intent considerably over releases, but the comments remained the same, either because nobody bothered to change them, or more likely because people think it's rude to change someone elses comments ( don't ask me why )

I'm not a big fan of comments. I don't consider javadoc and the like to be comments, though, that's code-borne documentation
 
todo's

arty said:
I come across these situations relatively rarely. The comments I hate the most are 'TODO' ones all the time :p

arty

TODO comments - used wisely - are extremely useful. lots of compilers such as Eclipse will keep track of them for you. our team has several different levels of TODO, and we all put our names beside them when we write them. anything that is a rush-job to meet a release is given a FIXME, and after the release the compiler shows us exactly where we put them all, and we can fix them for the next release, without having to keep a log of where they are. TODOs, we use to mark less urgent problems, or to mark pieces of code we suspect could be written better. Since they're sat right there in the source code, any developer on the project can see them, and fix them if possible. whenever I finish a major piece of the project toward the end of a day, I'll sit and go through some TODOs getting rid of them, rather than start something new for an hour
 
the_gof said:
TODO comments - used wisely - are extremely useful. lots of compilers such as Eclipse will keep track of them for you. our team has several different levels of TODO, and we all put our names beside them when we write them. anything that is a rush-job to meet a release is given a FIXME, and after the release the compiler shows us exactly where we put them all, and we can fix them for the next release, without having to keep a log of where they are. TODOs, we use to mark less urgent problems, or to mark pieces of code we suspect could be written better. Since they're sat right there in the source code, any developer on the project can see them, and fix them if possible. whenever I finish a major piece of the project toward the end of a day, I'll sit and go through some TODOs getting rid of them, rather than start something new for an hour

I suppose I'm lucky enough to work somewhere where you're given the chance to write things fairly well in the first place, even if it takes longer than initially planned. I wish they were 'TO DO' though :p

In addition, when I've seen them they have always been things like

Code:
#region Highly Important Tests
[TestFixture]
public class ImportantTests
{
 // TODO
}
#endregion

...on code I have to work on :p

arty
 
arty said:
I suppose I'm lucky enough to work somewhere where you're given the chance to write things fairly well in the first place, even if it takes longer than initially planned. I wish they were 'TO DO' though :p

In addition, when I've seen them they have always been things like

Code:
#region Highly Important Tests
[TestFixture]
public class ImportantTests
{
 // TODO
}
#endregion

...on code I have to work on :p

arty

we'll be like that as soon as the rush of our first release is over! our boss is a MAJOR agile methods guru, he encourages TODOs and stuff in a big way :-)
 
Back
Top Bottom