views:

699

answers:

20

As a student in computer engineering I have been pressured to type up very detailed comments for everything I do. I can see this being very useful for group projects or in the work place but when you work on your own projects do you spend as much time commenting?

As a personal project I am working on grows more and more complicated I sometimes feel as though I should be commenting more but I also feel as though it's a waste of time since I will probably be the only one working on it. Is it worth the time and cluttered code?

Thoughts?

EDIT: This has given me a lot to think about. Thanks for all your input! I never expected this large of a response.

+10  A: 

If you ever look at code you wrote 6 months before, you will be wondering why you did not comment better.

Romain Hippeau
...and if you forgot to update every comment relevant to every change in the past 6-months then you'll be pulling your hair out when your code says one thing and your comments another...
STW
if the code says one thing, and the comments say another, both are probably wrong.
Malfist
@Yooder: What would you recommend then? Do you have any suggestions on making sure that your comments and code stay synced up?
Tarmon
Comments are done by people doing a good job, Enforcement needs to be done by pier review, whether that is pair programming or code reviews. Of course if you are on your own, you need to wear different hats. I am surprised that a comment on keeping docs in sync with code has such high marks. Whether comments are good/bad relevant/not is where experience and diligence come into play.
Romain Hippeau
@Romain: Enforced mandatory commenting invariably leads to copy/pasted or autogenerated comments that have a net negative worth because they contain zero information, clutter up the code and are never updated when the code changes.
Michael Borgwardt
+20  A: 

Well considered comments illuminate when the code cannot. Well considered function and variable names eliminate the need for copious comments. If you find it necessary to comment everything, consider simplifying your code.

Bob Kaufman
+1 -- Comments should only be used to describe things which can't be described in code. If you're just describing your code then consider rewriting it to be more self-descriptive.
STW
This is something I have thought about as well. I imagine at times it may seem unnecessary at the time to comment but down the line you regret the decision.
Tarmon
@Tarmon - Experience has taught me that one rule for commenting doesn't apply to all situations. Although my response, above, guides me in most situations, I've found notable exceptions. For instance, when tracing through a colleague's code that doesn't make sense initially, I find myself leaving something akin to a trail of breadcrumbs that explain each minuscule discovery I make.
Bob Kaufman
+1  A: 

If you ever decide to open-source your personal project, people will thank you for your comments (unless they're terrible). If you hit upon a spectacularly great idea and your personal project turns into a business, then you'll be hiring more developers, and again your comments will be valuable. If you suffer a mild head injury, then when you return to work you'll be thankful for your comments.

Pointy
This + If you discontinue development for a long time, and restart after years, then you'll be thankful for your comments.
Tom
@Tom that's right, except that I would change the word "years" to "weeks" :)
Yar
Probably would actually suit me better, my memory isn't trained the way it should be due to an excessive amount of virtual notepad possibilities these days!
Tom
This is a good point. I am creating an Android app for a local bus service so at some point when I finish school and leave town I imagine I will hand this off to someone else.
Tarmon
A: 

I used to be in the exact same situation as you. When I first started I never commented anything because everything was extremely small and I always knew how it worked. But as I continued to expand my code and everything started pointing to each other, I found myself not knowing what certain things did anymore and got lost. I had to rewrite a lot of things so I knew what they did again, and I started commenting everything so I knew exactly how it worked and how to use it in the future. You may think you know how everything works now, but in the future you'll look back at something and say 'HUH?' It's better to comment things now and save yourself the trouble later.

The way I comment things:

Always add this at the top of any function, so you know what it does.

/**
 * What the function is supposed to do, a brief description of it.
 *
 * @param     paramter_name     Object-type     A description of it, do for each parameter.
 *
 * @return    Object-type - A brief description of what is being returned.
 **/

Then throughout your code make sure you comment things that look complicated. When you run checks, put a quick comment like 'make sure this is valid'. For any long lines of code or large blocks of code, add a comment of what that specific section does, to easily find it later on.

animuson
A: 

Commenting is useful for individual project as well as group projects especially when you will need to maintain or enhance the code over an extended period of time. This scenario may not be applicable for school projects, but in the workplace it is definitely applicable. If you have ever had to look at code that you wrote 6 months in the past then it might as well have been written by somebody else.

Taylor Leese
+3  A: 

Comment -- or better yet, recode -- anything that is non-obvious now. Later it will be completely non-obvious. You might think, "but it's going to be me," but if your way of thinking (and ways of coding) changes as you grow what's obvious to you now might not be obvious to you later.

Yar
+2  A: 

Some people treat comments as a code smell, a sign that the code could use more descriptive names and a better structure. They will fix the code so it does not need comments.

This works in a lot of cases. However one type of comment that is useful is 'why' something is being done. Sometimes fixes are made for obscure reasons that would not be obvious when reviewing the code later. The comments should not express what the code does (that should be covered by naming) or how it does that (again, the code tells you that), so save your comments for 'why'.

I find that nothing serves as better documentation as to how something works then unit tests.

Frank Schwieterman
+8  A: 

If the code is well written, with short methods (see Composed Method pattern) and meaningful names, then the code needs very little comments. Only comments which explain the "why" are useful - the comments explaining "what" should be replaced by improving the code so much that it's obvious what it does. Comments should not be used as an excuse for writing bad code.

Public APIs, especially in closed-source apps, are perhaps the only place where thorough javadocs are recommended - and then you need to take the effort to maintain them and keep them always accurate and up-to-date. A misleading or outdated comment is worse than no comment. It's better to document what the code does by writing tests for it and using good names for the tests.

The book Clean Code has a good chapter about comments.

Esko Luontola
+4  A: 

Unit tests and the like are the best forms of code documentation. Some testing frameworks write out a spec of what the class under test should do, giving people a great introduction to how a piece of code works in pure english while also providing very clean way to implement the tests itself.

Examples of that are Scala's ScalaTest or RSpec for Ruby.

I find that unless some weird hacky thing is required by the code in question, it is usually not beneficial to comment it. Also, it adds a lot of overhead because you have to maintain the comments... and maintaining the code and tests is already enough work.

Remember, code with out-of-date comments is worse than no comments at all!

A lot of the time, comments just says what the code does anyway, which is a waste of human effort. And if it doesn't, your code probably sucks and you should refactor it.

Just use testing frameworks.

egervari
+1 for including this popular point of view.
Yar
+3  A: 

Have you read Code Complete yet? Recommended as a very good read, and a great way to figure out some of the things CS profs drill down your throat.

Code comments come in two variety:

  1. Comments to explain logic, making sure that the code matches the intent. Often people will write high level pseudocode and will use that in comment form to fill in the actual code of what the module will do. Then they leave the comments as a read-along which can be used during later review.
  2. Comments to explain usage of a module. Think javadocs. Your intent here is for the consumers to understand why your code is important. One use of javadocs is in the Visual Studio Intellisense (since I don't use Eclipse idk). It shows the comments from the javadoc in the intellisense hover. Becomes VERY handy later on.

When professors ask you to document everything in your code, I have found the usage of psuedocode translated to actual code to be sufficient. However, in practice I've not found that many devs need it, as usually the code is sufficient to explain itself (when simple, well written, not relying on tricks, and when using descriptive variable names).

But I still put in comments about intent if I think it's the least bit unclear. This is just a bit of best practice.

But I definitely say read that book. ;)

drachenstern
Just when I'm about to read that book, I always think, "first I'll learn objective-C/Ruby/whatever, then Code Complete." Is there a cliff notes' version?
Yar
Cliff's Notes of Code Complete ... "http://stackoverflow.com/questions/tagged/best-practices"??? I can't say that there's a good short version of the book. Plus he's just a good author. Also, the things he talks about in the book will pay off when you decide to learn ObjC/Ruby/whatever. Consider it the next book you should read.
drachenstern
+1  A: 

Whenever i'm doing something that isn't self-documenting, i'll put a comment. I will forget what i was doing unless i do. But i prefer to write code that's so obvious that comments don't help much. Wherever possible, the code should be clear enough that thousands of lines of comments would be unnecessary.

Whatever you do, do NOT write comments like this...

// add 1 to i
++i;

That's noise. You're actually worse off with comments like that than with none at all.

cHao
Another point to consider here is that on a very simple loop (like if you wanted to initialize all the locations in an array to zero) you might use just i, j as iterator indexes, however, for anything more complicated, convert the i into something more readable. Especially if your code inside the loop is complex (although then it would be better to write as a function, passing the row index, yes? So we return to super simple loop and i is acceptable).
drachenstern
Thinking about this some more: Your example is for ++i; but what if we wanted to use the sideffect (yeah, I know, side effects are bad, but this is a contrived example) of /* increment i and add new value to x */ x = ++i; /* this does not give the same result */ x = i++; ~ Like I said, very contrived, but noteable. But it's an example of when add 1 to i becomes relevant. ~ Was this a useless comment?
drachenstern
Semi. But it's also an example of "The code should be clear enough that...comments would be unnecessary". If you need code like this, then what you really need is to break up the code into "x = i;" and "++i;" in the proper order.
cHao
+1  A: 

A hard-core stance is: "if you have to write a comment for your code, your code is broken". Rather than writing explanatory comments, refactor your code so that the comments become less necessary. This applies especially to function names (including their parameters), since they tend to be modified the most, and the comments seldom are updated to match.

Instead of:

// Compute average for the two times
int a = t1 + (t2 - t1) / 2;

write

int averageTime = AverageOfTimes(t1, t2);

int AverageOfTimes(int t1, int t2) {
    return t1 + (t2-t1); 
}

Stale comments are one of the leading causes of WTF's when I'm reading other people's code. Overcommenting has been cited as a "code smell" by several authors, including the authors of "Clean Code".

Personally, I write an explanatory comment for each class (I code in C# and C++ mostly), and occasionally when I am using an algorithm I want to refer to.

John Källén
You forgot the divide by 2 in your function version. ;)
animuson
That forgotten /2 might actually be a good illustration of the value here -- IMHO, it's actually easier to see that something's wrong in the second example than the first.
Weston C
Heh, haste is waste. In my defense, I had no unit tests for the sample code <g>
John Källén
No defense. Also, had you coded with pseudocode interspersed, it would've likely shown up before code review, not during code review ;)
drachenstern
I think this is an excellent point regardless of the example code ;). I definitely agree that making your code more descriptive is a great idea.
Tarmon
A: 

I have found that--as everyone will tell you--if you are coming back to code after several months you will have forgotten everything. That said, I hardly comment my own code except for comments like // ew.. hacked because X-beyond-my-control doesn't do Y correctly. But this is because the code itself is written very cleanly and is very easy to read. For instance, all variable and function names are completely descriptive. I don't use abbreviations except for rather long words which are obvious such as 'info'. All functions are extremely brief. All functions do one thing if possible. Nesting is avoided if possible. Logically related functions are grouped via classes or modules.

When I read other people's code, I don't read the comments. I read the code. And the difference between clear and well written code and spaghetti is far more important than any comments. Usually I don't care what their intent is/was; I want to change the code. And to do that it easily it needs to be well organized. So the comments are peripheral. But perhaps this is just me.

Fletcher Moore
A: 

Technically speaking the code is perfectly self documenting. I like to comment anything that is non-obvious or especially complex. I tend to like to have at minimum summary on a class, and maybe a short blurb for each member. When you have to write a huge amount of doc on a very large and complex method that is usually a good sign that it needs to be looked at for a refactor.

foreach(var a in b.Items) //Enumerate the items in "b"
{
    if(a.FirstName == "Jones") //See if first name is Jones
.... 

You want something in the middle of the above and no commenting whatsoever.

TheHurt
A: 

commenting is always useful!And I dont thik that commenting is a waste of time!It helps other developeres understand your code and it helps you when you haven't work on a project for months.

kafrlust
+1  A: 

To be honest, if code is clear its not necessary, but comments are best when a specific logic breaks given certain data (which may not be obvious). Leaving comments of issues that may occur is a great way to help prevent accidental bugs due to misunderstandings of what data to expect (or specifically not).

msj121
A: 

University software courses often push people towards excessive commenting as a way of forcing students to think twice about what they have typed. A nasty rule-of-thumb that was put my way when I was marking undergrad coursework a few years ago suggested a comment every 5-10 lines. Think most Java courses tell you to limit methods to circa 30 lines, so lots of comments within a function is a sign you should break it up.

My personal preference is to limit comments to documenting function purpose/inputs/outputs and data structures. Otherwise comments ought to be limited to things that require particular attention (eg things that looks out of place, perhaps bugs, at first glance).

Remy
A: 

The first comments are the variables and methods names. A lot of attention shall be paid to choose them. Do not hesitate to rename them if you can think of a better name.

Consistency and convention also help. Try to avoid NumberOfStuff, ThingCount, FooSize, always use the same form, possibly something in line with the language (does it have Array.length, or Vector.size). Always name similar things with similar names.

"Code never lies. Comments sometimes do". One day or the other, someone will modify the code and not the associated comment. Better spenf more time writing self-explanatory code complemented with some clever comment, than splitting out code and then explaining things with a lot of comments.

philippe
A: 

Rule #1 Comments should indicate WHY not 'what' (the code already tells you 'what' is happening)

Rule #2 After writing the comment - rewrite your code to read like the comment (then remove the comment)

kellyfj
A: 

While good variable and function names etc. may lessen the need for comments, any sufficiently complex program is going to be hard to understand merely by looking at the code alone, no matter how carefully it was written.

In general, the larger the body of code and the longer you expect it to be in use, the more important it will be to write detailed comments. It is perfectly reasonable for teachers to demand detailed comments because they don't want to have to spend a lot of time trying to understand large amounts of code from different students, but you don't necessarily have to maintain that same standard outside the classroom.

Regarding commenting functions & classes and the like, I find that only the most trivial functions are so self explanatory that a comment won't save the reader some time. Also, when you are using a smart IDE for a language such as Java or Curl writing properly formatted documentation comments will allow developers to see documentation for functions and methods simply by hovering over a call signature. This can save you a lot of time when working with large systems.

Christopher Barber