views:

1708

answers:

38

What are good arguments to convince others to comment their code?

I notice many programmers favor the perceived speed of writing code without comments over leaving some documentation for themselves and others. When I try to convince them I get to hear half baked stuff like "the method/class name should say what it does" etc. What would you say to them to change their minds?

If you are against commenting, you please consider answering the opposite question When NOT to comment code instead, or just leave comments. This should be a resource for people trying to convince people to comment the code, not otherwise. :-)

Other related questions are: Commenting code, Do you comment your code and How would you like your comments.

+15  A: 

Perhaps it's just something that has to be learned from experience; specifically, the experience of coming back to your own code after six months, and trying to work out what the hell you were thinking (or what you were on) when you wrote it. That certainly convinced me that comments weren't such a bad idea.

Jason Etheridge
I'm upvoting this because we both used basically the same example. Kind of scary. By the way, I've totally read through code and thought, "What was this moron SMOKING?" before realizing that it was my own code.
Max
I'm not so sure about this... I believe it's still easier to reconstruct your own past mental states than someone else's past mental states.
Thomas Kammeyer
Thomas... you're a more mentally acute man than I. I regularly have trouble figuring out what I was thinking when I got dressed this morning! :-D
Max
I have done this many times. Maintaining your own code is absolutely the best incentive to write it well.
JosephStyons
This is why I comment code. So I know why the hell I did this
Booji Boy
+20  A: 

Show them their own code from 6 months ago. If they can't understand and outline exactly what it does within 2 to 4 minutes, your point has probably been made.

Max
Excellent point - totally agree. To follow-up that, you should be able to give it to any decent programmer on the team and that person should be able to tell them what their code does in 2 to 4 minutes as too.
Tall Jeff
+11  A: 

Give them some (~500 lines, minimum) horrible, uncommented spaghetti-code to refactor. Make sure variables are not logically named. Whitespace optional.

And see how they like it!

Overly harsh, but it gets two points across in one go.

  1. Write your code well.
  2. Comment it so you and others know what it means.

I should stress that this code should not have originated from them. Comments are really useful for understanding your own code, months down the line, but they're also nigh-on essential for understanding complex parts of other people's code. They need to understand that somebody else might have to understand what they're doing.

One final edit: Comment quality is also pretty important. Some developers have an almost 2:1 code-to-comment ratio in their work but that doesn't make them good comments. You can have surprisingly few comments in your code and still have it make a lot of sense.

  1. Explain what you're doing. Your code quality should do most of this work for you though.
  2. More importantly, explain why you're doing something! I've seen so much code that says exactly what something is doing with no real idea why the developer (unfortunately me most of the time) thought it was a good idea in the first place.
Oli
I second you. I added the same answer, and deleted mine once I saw yours. :)
Vijesh VP
You're wrong, the example task you suggest might convince them to write cleaner code, but it has nothing to do with commenting code.
Stefan Rusek
So well commented spaghetti code would be ok, is that it?
AnthonyWJones
Stefan: My answer targets two problems. A short burst of nasty code might teach them to code nicer but a large block of interwined classes with no explanation of what/why they do what they do will teach them why God is in the comments...
Oli
Of course bad spaghetti code needs to be commented. Even if the spaghetti code had comments it probably wouldn't help. But if you write clear, concise code, you shouldn't need as many comments.
Kibbee
You should bold the "why". I was tempted to mark down before I saw that. The most important part of commenting is explaining the why, getting them to refactor code won't explain the point to someone who feels resistant to adding comments, it would just annoy them.
Quibblesome
I'd rather not train people to think that the solution to horrible, unmaintainable, bloated code is thorough commenting. At best that's just a band-aid, at worst you're enabling the horribleness to continue by reducing the pain of dealing with it by just that little bit.
Wedge
Your bold text "And see how they like it!" totally sounds like you want to be a dick, instead of actually encourage people to be good commenters.
Stefan Rusek
I agree with Stefan: looking for excuses to "punish" people is looking for trouble. Only bad managers try to get it done this way. Being heavy handed about convincing them is OK, but punishment and a sense of retribution are likely to prove worse than useless.
Thomas Kammeyer
If your developer is dumping thousands of uncommented lines of code into a shared codebase, they're the dick and they wont understand how bad things can get until they're on the receiving end. It's not punishment, just a bit of shock therapy and training. It's just an exercise.
Oli
Oli: it doesn't work. You can play with words as much as you want, the measure you recommended is inherently punitive and simply doesn't work in practice.
Thomas Kammeyer
It's the: "Don't touch that, it's hot!" versus the "He'll only burn himself once." argument. Some learn better from the former while others the latter. Oli's argument works great for the latter but will only piss of the former.
Nazadus
+4  A: 

I would say "yesterday I had to read some of your code. I was able to understand it but less than or equal to 5 well-chosen lines of commentary explaining how it accomplished its goals would've allowed me to read it in about one-tenth the time and then I could've worried about understanding a problem instead. I'm not stupid, and you're not smarter because you can write things that are difficult to understand. On the contrary, if you can't produce readable documentation+code ensembles then you're less of a developer."

I had this drilled into me long ago: if you write something and someone of reasonable ability can't understand it, then it's your fault, not his or her fault. This applies to writing in natural languages, and it applies to writing in programming languages.

Thomas Kammeyer
+36  A: 

Only comment the "why" and not the "what". In so far i agree, it should be clear from the class or method or variable name what it does and what it is used for. Refactor where it doesn't instead of commenting it.

If you take this approach, you will get comments, and you will get useful comments. Programmers like to explain why they are doing something.

steffenj
yes yes yes! "the method/class name should say what it does" is true, but the point of comments is the "why", i.e. the context, which the code does not state.
Steven A. Lowe
While I strongly agree, this doesn't answer the question at all, so -1 from me
hasen j
+1. For example: Unusualy complex code as a workaround for a bug in another companie's product or as a major performace gain.
Tim Matthews
+2  A: 

Well, there's always the "if you don't comment your code, we'll find someone else who'll comment theirs" approach.

More gently, tell them that they are sorely letting down the team if they don't document and comment what they are doing. The code does NOT belong to the individual, unless they are complete lone wolves. It belongs to the team, the group, whether that be a company or a community.

Kevin Little
+2  A: 

"Writing Code" = "Writing sequence of commands in a special language" + "Writing comments"

It shall be self-evident to comment code while writing it! Have you ever commented code that is already 3 or 4 months old? (Of course you have, and it was everything else but fun!)

If your project is already well documented, programmers who add new code may be motivated to write comments in a similar manner.

koschi
+4  A: 

There have been similar discussions about commenting. Here's the one on what rules people follow when commenting code: http://stackoverflow.com/questions/142830/what-are-your-hard-rules-about-commenting-your-code#142869. Some of the answers have also very good reasons why you would want to comment your code.

Franci Penov
+8  A: 

Remind them that reading the code can only tell them what the code does, not what it is supposed to do.

James Curran
Indeed: the interface specification tells what it's supposed to do. The comments tell you why the programmer thought that what it does is what it's supposed to do.
Steve Jessop
Whose to say that intent hasn't changed over time; while the comments weren't quite faithfully updated....
Chris Lively
+3  A: 

Lead by example. Developers are easily swayed when they see The Right Thing, so seeing solid practices in action may encourage them to do the same. Additionally, you could encourage your group to adopt code metrics that address code maintainability and comments. For example, Code Analysis will produce a bug for methods without summary documentation.

Gabriel Isenberg
+3  A: 

The best way to convince a person is to make them realize it on their own. Make them debug well commented code. It will show them what good commenting looks like - comments are no use unless they really communicate what is going on. They will notice how easy it is. Then let them get back to some of their old code. They will notice how hard it is. You have not only shown them what not to do, but what to do (this is more important). You don't have to do any more. What's more, you don't have to try and convince them verbally. They simply must understand the need to comment code in their own way. This is of course, assuming that the code that needs to be commented is not self explanatory.

carleeto
+5  A: 

I'm not being snarky at you, but you should rephrase the question to be How do you convince other developers to work as a team?

Seriously, some people assume you can read their mind.

If you're part of an agile team, code is collectively owned, so when you see uncommented, awkward, or hard to read code, go ahead and change (refactor) it so you understand it. If people complain, tell them why and be upfront. That you found it incomprehensible, and nobody owns the code.

Robert Paulson
+1; it isn't "their" code.
Adam Jaskiewicz
+2  A: 

Have them use an unfamiliar API, but do the programming on a non-Internet connected machine(if you can find them these days) so that they don't have any access to the API documentation. This is effectively what they are forcing other developers to do if they are trying to use the code of the non-documenters!

cdeszaq
+24  A: 

My opinion:

I wouldn't. The method/class name should say what it does. If it doesn't, either the method or class is trying to do too much, or it's named poorly.

I'm a fan of commenting why, not what. If it's not clear why code is using one approach over another, comment it. If you had to add a hack unused variable to get around a compiler bug, comment why. But comments like "//Connect to database" are signs of bad code or bad policies. A method named ConnectToDatabase() is much better. And if it has "//Determine DB server IP" in it, perhaps that should be pulled out to a method named "DetermineDbServerIPAddress()".

Design can be documented, but comments are a generally a poor place for that level of documentation. With knowledge of the design, and some comments on why, the what and how should be obvious. If it's not, rather than convincing them to comment their code, get them to improve it.

Philip Rieck
Someone finally says it right. Totally agreed.
mattlant
+2  A: 

You also have to differentiate two different comments here:

  • API comments (javadoc or other similar kind of documentation): you can ask for them to _**use their own code in a limit scenario**_ (boundary conditions like null objects or empty strings or...) and see if they actually manage to remember what does their own functions in those case
    (That is why I am for a complete javadoc including limit-value)

  • Internal comments (within the source code): you can ask them to explain any function they have coded, just pick a function with a _**really high cyclomatic complexity level**_, and see them struggle around all the different code workflows and decision branching ;)

VonC
+2  A: 

The current coding standards at my current place of work is to comment every function. Blanked rules like this are harmful, and should never be in place. There are situations (and some of them common) where adding comments removes readability.

class User {
    getUserName() { /* code here */ }
}

What is the point in adding a function header to the above peice of code? What else are you going to say besdies "gets the username". Not all code needs to be commented. My rule of thumb is: skip the comments if you are not adding any useful information that the function signature does not.

Rontologist
+1  A: 

@James Curran I 100% agree! I can read your code and figure out what you told the compiler to do; but that doesn't mean it was your intent to make the compiler do that. I know I'm not an arrogent enough programmer to believe that everytime I write code it does exactly what I was trying to make it do. Additionally, I often find it helps me catch silly logic errors in my code by going through after I've written it and trying to explain what I intended for the code to do.

Timothy Carter
+1  A: 

One idea is to point out that it takes less than a minute to write one or two sentences per class and less than half a minute to write one sentence per method.

hstoerr
That simply isn't true. It can take developer much longer find the correct human language expression for what they are doing than it takes to actually write it. This is not a good use of time
AnthonyWJones
if they have so much difficulty writing English, then they'll have an even harder time reading the requirements! That's a good reason to make them comment what they *thought* they were doing.
gbjbaanb
+1  A: 

Tell them to document their functions and interfaces with Javadoc commments and then to run the code through Doxygen to generate cool-looking HTML documentation for their code. The coolness factor can be a good motivator sometimes.

Ates Goral
+3  A: 

Comments should be thorough, written at the level of intent (why not how), and rare.

When writing code I tend to comment reasonably heavily as a matter of course. Then, I go back through and try to delete as many comments as possible, without decreasing the understandability of the code. >80% of the time this is as easy as extracting a well named method, this usually results in a comment which merely duplicates the information in the code itself. Beyond that, if there's a section of code that "needs" a comment I look for ways to simplify it or make it clearer.

Code should be self-documenting, and with the right techniques you can get 95% of the way there pretty easily. Generally I consider it to be a failure if there are any comments remaining on code that I check in.

Wedge
A: 

Writing down what a method / class will do before actually coding it helps a lot to get it right - and you have commented it.

hstoerr
Writing a unit test for what it should do would be a better use of your time
AnthonyWJones
+7  A: 

If you or the other developers have not read Code Complete (or Code Complete 2) yet then stop what you are doing and read it.

One thing that standands out is "A function should do just one thing and do it well". when such a function is named after the one thing it does well what further need is there for comment?

Comments have the habit of going out of sync with the code they're supposed to be describing. The result can be worse than not having the original comment in the first place. Not only that but developers know that comments can age and can't be trusted. Hence they will read the code and discern for themselves what it is actually doing anyway! This kinda nullifies the point of putting the comments there in the first place.

Having said that the same can be true of a function name, it may have been well named originaly but overtime new operations have been added to it that are not alluded to in the name.

All comments seem to do separate out the lines of code a developer would prefer to be closer together so that they can see more per screenfull. I know my own re-action to a piece of code with lots of comments that I've got to understand. Delete all the comments. There now I can see what the code is upto.

At the end of the day if your going to spend time making things right your time is far better spent refactoring the code to ensure its as reasonablly self-describing as it can be rather than just writing comments. Such an excercise pays off in other ways such as identifing common chunks of code.

Its worth bearing in mind also that many good developers much prefer writing crisp clean C#, Java, whatever than the far less precise human languages with all the assumptions and ambiguities that they have. True most people with common sense would know how much detail is enough detail but good developers are not 'most people'. Thats why we end up with comments like \\adds a to b and store it in c (ok thats too extreme but you get the point).

Asking them to do something they hate doing and are frankly not very good at (even if you're convinced its the right thing to do) is simply a battle already lost.

AnthonyWJones
I don't agree at all. I've worked on code that does complex calculations efficiently and which uses separate functions to compute different parts of a summation for good reasons. It needs a few simple, well-chosen comments to relate the equations to the code.
Thomas Kammeyer
The average coding exercise though is not full of complex calculations. The vast majority of it is very boring and when the code is structured well with good naming its self-documenting. Do like commenting stuff?
AnthonyWJones
+1. Very well said! Only write comments if they don't rephrase what is already stated in code.
Dimitri C.
+5  A: 

Our strategy is to have systematic code reviews, and to reject code that's not properly documented (through comments, proper function naming and organisation, etc...). If it's not clear to the reviewer, you go back to the work bench, period.

Kena
A: 

Only employ good engineers who ensure their code implicitly states the intention (using comments and otherwise). Anyone who wants a job will have to do it right. Harsh, but fair, IMHO.

Jeff Yates
A: 

I am also in the camp of less comments the better, and in order for that to work it requires clear concise code that is to the point. So that is where i would start with them. Tell them they dont have to comment, as long as they write better, clearer, self commenting code.

mattlant
A: 

Only put comments in when you absolutely need to, when it is not clear why the code is doing what it is doing.

e.g. If you have a comment above a dozen lines of code then just refactor into a method using a good name for the method or just add the comment to aove the method

Craig Angus
+2  A: 

I use one subtle technique:

I set the level of warnings in the project to be reported as errors. And our Continuous Integration server is building the whole solution along with XML documentation upon each ckeck-in.

If developers do not write the comments, the build fails! And after that, they have to write the comments, so after a while, they got used to it.

It isn't aggressive in terms of pressure, but i find it like nice way to correct their behavior.

ljubomir
To force them is not exactly subtle. :-) But if you start a new project this can be a good idea - at least for APIs and the like.
hstoerr
+3  A: 

Depends on how much power you have...

I found a very effective way was to make it a fixed part of peer based code reviews - points for comments. If there was a remark that the code was badly commented I would make the developer comment it to my satisfaction, which basically meanth they had to describe enough of the code for me to understand it by printing it out and reading it. And I would do it too.

Remarkably this was popular with the developers, even though it sounds dickensian. Two things happened. First, people started to comment their code. Second, badly commented code became a sign that the developer didn't quite understand what they had written (otherwise they would have described it).

The only real downside was that the comments had to be kept up with the code when it was revised for bug-fixes etc. This was almost impossible to enforce in a real development shop, but once enough good practice was engrained it sort of happened naturally.

BTW I prefer comments in the code itself rather than a Dostoevsky novel as a doc string. The former is a useful aid to subsequent programmers. The latter is just a long piece of out of date text that fills up the docs and misleads everyone.

Simon
+4  A: 

Show wisdom in your desire for comments, and they will be more likely to listen.

Less is more.

Emphasize quality over quantity.

In my team, there was a push to comment everything in certain API's. Some developers began using a tool that would automatically generate comments by looking at the method names and signatures.

For example:

/// <summary>
/// Gets the Person.
/// </summary>
/// <returns>
/// A Person
/// </returns>
public Person GetPerson()
{

}

Can you think of a bigger waste of screen real estate? Can you think of a bigger waste of brain cycles than reading comments that provide no new information?

If it is obvious from the method signature, don't say it! If I can figure it out in a few seconds, don't put it in a comment. As others have put it, tell me why you chose to do it that way, not what you did. Write your code so that it is obvious what it does.

Neil Whitaker
A: 

Almost a rhetorical question. Really good coders actually do not need many comments. Unfortunately there are precious few of these. So you're telling people their code will not be readable without comments.

Programmers hardly ever get enough time to do a pretty job. It seems like we're always in a headlong rush to get something to unit test to see if it's going to start spitting out results. So my final answer would be to find a workplace that has an atmosphere that makes it possible for an average programmer to have time for quality. Me, I've applied with Google twice and got rejected twice.

I think the really good coders put comments in anyway as a matter of course. Perhaps that says something about the quality of a coder.
gbjbaanb
+1  A: 

If developers have to take part in code reviews and are exposed to good commenting they should be able to get the clue. If they do not see the practice as useful then they should get some feedback from their peer reviewers.

Failing that (assuming you're the supervisor / manager) make it part of their performance appraisal. If you can measure it, you can appraise based on it.

Ensure that it's a REVIEWED commenting that you score on, as the passive-aggressive devs will document every last statement as a not-so-subtle FU.

Todd Williamson
A: 

I've never in ten years of development seen a comment that actually told me something useful about the code. Comments are usually out of date or state the obvious. As soon as you write them it's one more thing to maintain. I think the only reasonable thing to comment would be a regular expression or perhaps assembler code.

If you need a comment chances are you need to pull out what you wanted to comment into a separate method or class. Another way to document your code is to write tests.

Historical comments such as "changed to support feature X for customer Y" are invaluable. I agree that a decent programmer should be able to understand *what* the code does, but only a psychic will know *why.*
Adam Liss
+1  A: 

I've become a firm believer in what I call Headrick's Rule, named for a coworker of mine who discovered that a good way to motivate someone to do something is to make it painful for them not to do it.

In your case, asking your non-commenting developers to spend an hour or two explaining their code, perhaps to a "slow" audience, perhaps during their lunch hour "to avoid project slippage" will go a long way. Smart people--even stubborn ones--learn fast!

Adam Liss
A: 

While commenting can be used well to provide insight into the code I would argue that it is MORE valuable to encourage programmers to write descriptive code than to leave comments. Writing smaller methods with clear names and signatures will serve you better in the end than long rambling comments explaining code that could have been written better to begin with.

mcrute
Maybe. But is this a reason not to comment the code? A little goes a long way and is not much effort - you can have the best of both worlds.Anyway: your answer is an answer to the opposite question http://stackoverflow.com/questions/163600/when-not-to-comment-code
hstoerr
A: 

It's a sad fact that the overwhelming majority of programmers won't comment their code properly until they end up on the other side of bad documentation. Being stuck maintaining an app lacking clear comments is just awful. Usually right after that (IME), comments in the code flow.

Yes, this happened to me and I comment thoroughly now.

cciotti
A: 

I also think the best way to show developers how important good comments are is to show him his own code from the past.

Also show them the advantage of something like SandCastle.

Flo
+1  A: 

"blabla comment the why not the what blabla"

An easy answer for every question about commenting code... My problem with that is everyone is talking about the "why" and "what" like they were the same thing for everyone everytime.

It's obviously not the case. When I discover something new (an API, a framework, a new project, a tool...), there is a lot of things that i don't understand or i don't even know about the existence. But after some time, a lot of things become more meaningful. I haven't to lost myself in a code jungle to understand what a class is for.

At first, the "why" and "what" are the same thing, and this thing can be summarized into "?". After spending some time to learn and understand, the "what" becomes more and more easy to grasp, and finally becomes so obvious that i even forget its presence. As the "what" becomes "clearer", my mind has more resources to ask itself about the "why", and my understanding of the whole architecture becomes more and more complete.

If i put comments in the code at the beginning of my learning time, even if i'm trying to comment the "why" i will comment what more experienced people already consider obvious (they will call it the "what" and say the comment is useless). Comments written after the bigger wave of the learning curve has been crossed will be both fewer in number and describing a very specific feature of the commented thing (only understandable by those who have reached this level of understanding).

The last thing about this is : i have never lost time reading comments, and they have often reduced my learning time. I have never seen a "too commented" code. I have often read comments that were not useful to me (like everyone), but i never thought "if only i had spent all this time reading comments doing something more useful !". Given the fact that all modern IDE provide ui able to hide big comments, i don't understand why it could be considered bad to write a useless comment.

From a more subjective point of view, i prefer to see a few useless green words in a page of code than a few words indented on an empty white background.

i prefer a useless comment in an obvious part of code than nothing in a 15 pages long dark method....

A: 

In my opinion (and I'm talking about .Net programming here) if you have to put a comment you have failed in making the code readable. The answer is usually refactor!

However, if you feel you have to put a comment then it should always be a "why" type of comment and not a comment that explains what the code does.

Paul
And how would you refactor out a 'why" comment? ;-)
hstoerr
Now I didnt say that did I ;-)
Paul