One of my team members consistently avoids making comments in his code.

His code is not self-documenting, and other programmers have a difficult time understanding his code.

I have asked him several times to comment his code, however he just gives excuses or claims that he will do it later. His concern is that adding comments will take too much time and delay the projects.

What argument can I present to him to convince him to properly document his code?

On that note, am I wrong to focus on the code comments or is this indicative of a larger problem which should be addressed?

Commenting for comments sake does not make the code better. If the code is understandable (including why) without comments then fine otherwise comment.
–
Loki AstariFeb 5 '13 at 6:37

56

Oh yeah, and when the complexity of some piece of code triples in order to solve a race condition or deadlock, don't comment on that! Let people solve the puzzle of why the code has to be the way it is, and why it breaks in mysterious ways if they make experimental changes. Everyone should be a chess grandmaster of concurrency ...
–
KazFeb 5 '13 at 9:28

12

@Kaz Sarcasm (I hope) does not translate well to text.
–
dewordeFeb 5 '13 at 10:23

following Dale Carnegie's principle you should try to understand why he don't want to comment..you mentioned that he don't want to delay the project..so you can say to him that if he doesn't comment other's would not be able to understand the code and that would further delay the project..this should definitely help..
–
AnirudhaFeb 5 '13 at 13:28

23 Answers
23

Comments alone don't make for better code, and just pushing for "more comments" is likely to give you little more than /* increment i by 1 */ style comments.

So ask yourself why you want those comments. "It's best practice" does not count as an argument unless you understand why.

Now, the most striking reason for using comments is so that the code is easier to understand, and when people complain about lack of comments, they are either clueless parrots, or they have a hard time understanding the code they're working with.

So don't complain about missing comments: complain about unreadable code. Or better yet, don't complain, just keep asking questions about the code. For anything you don't understand, ask the person who wrote it. You should be doing that anyway; with unreadable code, you'll just ask more questions. And if you come back to a piece of code later, and you are unsure you remember correctly what it does, ask the same question again.

If comments can fix it, and your colleague has a functioning brain, he/she will at some point realize that commenting the code is much easier than having you around asking stupid questions all the time. And if you can't come up with questions, then maybe that code is perfectly readable already, and it's you who is at fault - after all, not all code needs comments.

On the people skills front, avoid sounding condescending or accusing at all cost; be serious and honest about your questions.

What if the answer to any question about code is along the lines of "What have you done to understand it?"
–
SaulFeb 5 '13 at 9:58

36

+1: Pushing for readable function names can have added benefits... At Code Review: "Can't understand what xg_jkhsfkasq is doing". "Oh, it's flushing the primary feed buffer, now can I release?" "Sure, but I'm hesistant to approve it till you've renamed the function flush_primary_buffer" "Ah, but it's also clearing the main cache, so that name would be misleading" "IT'S WHAT? Don't clear that cache, it'll grind the system to a halt! While you're changing that logic, would you mind renaming that function?"
–
dewordeFeb 5 '13 at 10:03

15

I'd be worried about giving the impression that I'm unable to read code. A non-technical manager might just notice that I'm constantly asking 'Bob' for help because Bob's code is too advanced for me. That would mean Bob is an 'advanced' developer and I am not ready to work at his level.
–
Rob P.Feb 5 '13 at 10:03

5

@Rob P. I see the fear, but if you can't read the code and it's expected that you will maintain the code, then the code is not well written, or you don't know enough. If you don't know enough, you need to ask. If asking reveals that the code is simply difficult to read, push for it to be fixed. The trick would be, if you're going down the social engineering route, to mix it up whether Bob goes to your desk or you go to his, and to be very active about pointing to things. After all, a non-tech manager won't be able to grasp the content of the discussion...
–
dewordeFeb 5 '13 at 10:13

I have met lots of devs who had trouble of writing self-documenting code or helpful comments.
Those kind of people most often just lack enough self-discipline or experience to do it right.

What never works is just "telling them to add more comments" - this will increase neither their self-discipline, nor their experience. IMHO, the only thing that does work are frequent code-review / refactoring sessions. Whenever the dev has completed a task, go with him through his code, and let him explain any function or code piece you don't understand. Immediately refactor or document the code in a way so that the two of you will understand it 6 months later.

Do this at least some months, and if you are lucky the other devs learns enough from that sessions that you can reduce the review frequency.

+1 this is the only way to actually implement change into a colleague that I've found, actually sit with them and review/refactor along side them. If you aren't in a position to deny a code review this can be difficult. Sometimes when you're mid-level you just have to raise issues to seniors and if they don't listen grind your nose out until you're senior and can veto such garbage
–
Jimmy HoffaFeb 5 '13 at 14:48

1

Code reviews & pair programming are the best way in my experience of improving the overall standard of developers in a team. It is about sharing knoledge and skills within the team. Without it you are makeing developers learn the hard way and assuming they came out of college perfect. The general lack of this practice around the industry is probably the reason why there are so many developers with 10+ years of experience that can't write readable, well organised code.
–
Martin BrownFeb 18 '13 at 13:25

I'm surprised no one has mentioned code reviews yet. Do code reviews! When he has a check in of bad quality don't just say "add comments". Constantly ask questions and get him to tell you what his code does and why. Take notes. Then, at the end of the code review give him a copy of the notes and tell him to make your questions fairly obvious. Either by more comments or by just refactoring his code to make it better quality (preferably the latter when possible)

+1 - If you have to ask a question about any part of the code then that part either needs a comment or a refactoring so the question doesn't need to be asked by someone else in the future.
–
DunkFeb 6 '13 at 14:16

This depends on the code your team worker produces. If you read the Clean Code book from Uncle Bob you will find that he actually prefers to not add comments to code. If the code itself is as readable as it should be, then there is hardly any need for comments.

If that is not the case, or you require comments due to some non-negotiatable policy, then the main question becomes whether it is only you who wants him/her to write comments, or whether it is the whole team or the team/project leader. If it's just you, then you should talk to your other colleagues to find out why it may not be such a big deal at all.

If the project leader lacks the comments you can also require them as part of completeness, i.e. if the submitted code lacks comment the work is not finished yet. He may not continue to do other work, until his current work is finished and for that comments are required. However, keep in mind that this kind of forcing will most probably result in horrible comments (expect loads of crappy repetition-of-code-comments).

The only feasible way in my humble opinion is to discuss the actual profits you and everyone else gets from comments. If s/he does not understand it by mere discussion, there's always the hard way too: instead of letting them write new code have them work on existing code. If possible you should find them two different work areas - one with proper useful comments and another that lacks comments. Having to read someone else's non-readable non-commented code is an eye-opener with regards to your own work.

We have all been there once and were angry for the original author of some source for working so sloppy. It's the additional reflection that each of us is such an author as well that makes you realize you should care about readability - hence, do not forget to discuss the results with your colleague afterwards in order to promote this reflection.

Re: "this kind of forcing will most probably result in horrible comments". If you aren't commenting as you code then back-filling comments after the code is done will almost always result in horrible comments whether you believe in them or not. When you are coding, that is the time that you know exactly WHY you are doing something a particular way. That's the time to let others know. If you comment after you're done, odds are you won't even remember what you were thinking when you wrote the code, so you tend to throw a useless comment in just for the sake of commenting.
–
DunkFeb 6 '13 at 14:13

3

always had a problem with that book's approach. Comments can be v. useful in explaining a business process/logic (or why) that no amount of clean code can.
–
bharalFeb 6 '13 at 16:45

2

Clean Code is a decent book, but it should not be treated as gospel. You have to apply common sense and decide for yourself what works. I disagree with the advice on comments, because programming languages are geared towards expressing the how of a problem with scant regard to the why. I was writing code for Google Shopping that appends a country code to the product SKU. It's obvious what the code is doing, but unless you know that you can only use the same product code once, even in different markets, you wouldn't know why I was doing this. The comment I added clarifies it.
–
GordonMFeb 17 '13 at 11:48

If you have an employee who can't follow instructions, reprimand him, and make sure it's clear that it won't help his career advance. Consistency in coding style is critical for a team, and if everyone else is writing comments and this one isn't, that will hurt the coding style.

That said, you can probably help him out. In my experience, when someone protests that commenting takes too much time there is a psychological barrier such as…

He is self-conscious about his code/design choices and doesn't want to lay them out in prose. (Code reviews can be helpful to bolster someone's self-confidence as much as to tear them down.)

He works very linearly and doesn't think ahead much. Commenting is painful because it forces him to unload the immediate code he was about to write from his working memory in order to compose his intent in a different way. (If this is true, commenting becomes very important for his code quality.)

Historically people don't understand his comments.

It's important for a programmer to realize that comments are like tests: They're not just for future use – They're for the programmer himself. They force him to think differently about his approach.

None of this is a substitute for CI, tests, or code reviews. It's just one of many critical parts of coding that is, itself, not writing code.

I don't think threats are necessarially going to be effective, they can come across as bullying (even if that wasn't the intent) and coders as a rule tend to be resentful of edicts from higher ups and in this case he may just dig his heels in even more. It may come to that as a last resort, but only as a last resort.
–
GordonMFeb 17 '13 at 11:50

We use Kiln, and we love it. We have a policy that every changeset must be reviewed (though we allow devs to raise/approve reviews for themselves on tags and conflict-less merges (though most of us use rebaseif); this way we can quickly spot changesets without reviews).

Code that is not clear is reason for a code review to be rejected. It doesn't matter whether the fix is comments or clearer code, but the reviewer must be able to understand it. Some devs prefer to rewrite the code, but others (myself included) often find it easier to express intention in comments (code can easily show what it does, but it's harder to show what it should do).

If there is ever question about the clarity of code, the reviewer always wins. Of course the author understands it, because they wrote it. It needs to be clear to another person.

By using software like Kiln, no changeset gets overlooked. Everybody in my dev team much prefers it this way. Code review software has had a huge impact on both our code quality, and application quality :-)

It's easy for devs to get defensive with rejected reviews when first introducing software, but in my experience, it doesn't take them long to realise things are better this way and embrace it :-)

Edit: Also worth noting, we try not to have devs explain cryptic code verbally or in comments in the review. If something isn't clear, the best place to explain it is in the code (in comments, or by refactoring), then add the new changesets to the same review.

This is just silly. I hope nobody believes that such poor commenting style is helpful. But do you honestly believe that comments should never be used?
–
jmkFeb 16 '13 at 22:27

1

Yep, this is a silly suggestion, if the code is incredibly readable I could understand few comments but seeing comments should say why the method is doing what it is and where it will be used once you get to more than a few classes there really is no reason for no comments, they help everyone.
–
G3DFeb 17 '13 at 0:56

3

The important thing to remember is that while everything makes sense to you right now, someone else will have to maintain your code in 3 years. Don't screw the over.
–
xaxxonFeb 17 '13 at 2:32

4

@xaxxon Not to mention that apples even if that person might be you.
–
fluffyFeb 17 '13 at 3:00

3

@mehaase - Not what, not how, but why is the most important reason to add comments to code.
–
Henk LangeveldFeb 26 '13 at 21:38

am I wrong to focus on the code comments or is this indicative of a bigger problem that should be addressed?

Somewhat. Great code doesn't need comments. However as you said, his code is not self-documenting. So I would not focus on the comments. You should focus on improving the skill and craftsmanship of your developers.

So how to do that? Doc Brown's suggestions about reviews/refactoring sessions is a good idea. I find pair programming even more effective, but it may also be considerably more difficult to implement.

Interesting, that readability as applied to natural language is measured by speed of reading and comprehension. I guess a simple rule can be indeed adopted, if a particular code comment does not improve this property, it can be avoided.

Why comments?

Although, code comment is a form of embedded documentation, there are multiple ways in high-end programming languages to avoid superfluous "over-documented" programming (of meaningful code) by using elements of the language itself. It is also a bad idea to turn code into listings from programming text book, where individual statements are literally explained in almost tautological fashion (mind the "/* increment i by 1 */" example in already provided answers), making such comments relevant only to programmers inexperienced with the language.

Nonetheless, it is the intention of trying to comment the "under-documented" (but meaningless) code that is truly "the source of all evil". The very existence of "under-documented" code is bad signal - either it is an unstructured mess, or wacky hack of mystical lost purpose. Obviously, the value of such code is questionable at least. Unfortunately there are always examples, when it is indeed better to introduce a comment into a section of (visually grouped) formatted lines of code than wrap it into new subroutine (mind the "foolish consistency" which "is the hobgoblin of little minds").

Code readability != code comments

Readable code does not require annotations by comments. In each particular place in the code there is always a context of a task that this particular code is supposed to achieve. If purpose is missing and/or code does something mysterious = avoid it at all costs. Do not allow weird hacks to populate your code - it is a direct result of combining buggy technologies with lack of time/interest to understand the foundations. Avoid mystical code in your project!

On the other hand, Readable program = code + documentation can contain multiple legitimate sections of comments, e.g. to facilitate generation of "comments to API" documentation.

Follow code style standards

Funny enough the question is not about why to comment code, it is about team work - how to produce code in highly synchronized style (that everyone else can read/understand). Are you following any code style standards in your company? It's main purpose is to avoid writing code that requires refactoring, is too "personal" and "subjectively" ambiguous. So I guess, if one sees the necessity in using code style, there is a whole serious of tools how to implement it properly - starting with educating people and ending with automation for quality control of the code (numerous lints, etc) and (revision control integrated) code review systems.

Become a code readability evangelist

If you agree that code is read more often than it is written. If clear expression of ideas and thinking clearly is important to you, no matter what language is used to communicate (math, machine code or old-english).. If your mission is to eradicate dull and ugly way of alternative thinking.. (sorry, the last one is from another "manifest").. ask questions, initiate discussions, start spreading thought provoking books on code cleaning (probably not only something similar to Beck's design patterns, but more like already mentioned by R.C. Martin) which address ambiguity in programming. Further goes a bullet-point passage of key ideas (quoted from O'Reilly book on readability)

Simplify naming, commenting, and formatting with tips that apply to
every line of code

Attack problems at the function level, such as reorganizing blocks of code to do one task at a time

Write effective test code that is thorough and concise—as well as readable

Cutting "commenting" out, one is still left with a lot (I guess writing code that does not need comments is one piece of great exercise!). Naming semantically meaningful identifiers is a good start. Next, structuring your code by grouping logically connected operations into functions and classes. And so on. A better programmer is a better writer (of course, assuming other technical skills given).

If a team member is having trouble understanding another team member's code (for any reason); then that team member should be able to find out who wrote the original code (any sane revision control system) and should be encouraged to ask the code's author to explain it directly (e.g. walk over to their desk, sit down and discuss it).

In this case, if the lack of comments is a problem then the person who isn't adequately commenting their code will spend a large amount of their time explaining what they've done; and (if they're smart) will start adding comments to avoid spending time on all those explanations.

Note that encouraging team members to ask each other for explanations is valuable for other reasons. For example, maybe a team member is less experienced and can learn things from the more experienced team members.

Mostly, by encouraging team members to ask each other for explanations you create a self-balancing system; where different team members "auto-adjust" to each other.

This is largely an extension of tdammers answer, but perform code reviews at regular intervals.

Having him (and other developers) sit down, walk through their code, and more or less defend in front of their superiors and peers will make everybody better coders and will add real value over a relatively short period of time. In the short term, it will give the developer in question no excuse to, at the time of review, properly comment his code.

EDIT: I'm unsure as to why somebody would downvote my suggestion - perhaps I took for granted that the benefits of code review would be common knowledge... please see this thread as to a community analysis of the practice:

Having people laugh at code in front of other colleagues is not the way to do :-\
–
Danny TuppenyFeb 5 '13 at 21:04

1

If the people doing the code review are laughing rather than being constructive they need training every bit as much as a developer that can't write readable code. Giving criticism that is constructive rather than derogative is one of the social skills I find developers often lack.
–
Martin BrownFeb 18 '13 at 13:10

Considering the often extreme views on commenting, I hesitate to weigh in. That being said...

What are some arguments that I can present that if you are going to
write (unreadable) code that it should be properly documented?

Understanding how to write maintainable and readable code takes time, practice, and experience. Inexperienced programmers (and sadly many experienced ones) often suffer from the Ikea Effect (PDF). That is because they built it and are intimately familiar with it, and they are sure the code is not only great, but readable as well.

If the person is a great programmer, then little if any documentation is required. However, most programmers aren't great and a lot of their code will suffer in the "readablity" department. Asking the mediocre or developing programmer to "explain their code" is useful in that it forces them to view their code with a more critical eye.

Does this mean "documenting" their code? Not necessarily. Case in point, I had a similar programmer with this issue in the past. I forced him to document. Unfortunately his documentation was as indecipherable as his code, and didn't add anything. In retrospect code reviews would have been more helpful.

You (or a delegate) should sit down with this programmer and pull up some of his older code. Not the new stuff he knows from just working on it. You should ask him to walk you through his code with minimal interaction. This could also be a separate "documenting" session, where he is to explain in writing his code. Then he should get feedback on better approaches.

As an aside... some documentation is sometimes needed regardless of how good the "readablity" of the code is. API's should have documentation, extremely technical and complex operations should have documentation to assist the programmer in understanding the processes involved (often outside of the programmers domain of knowledge), and some things like complex regex'es should really document what you are matching against.

No, that way developers are required to write some comments. Their usefulness decreases with the pressure to write them, often sinking below zero into the actively harmful region (invalid comment is worse than no comment) if the policy is pushed strongly.
–
Jan HudecFeb 5 '13 at 8:25

1

@JanHudec - I agree with you. That is why some control should be set. Automatic generation ensures that, e.g., function arguments in code are the same as in comments. Moreover, having a single PDF instead of a directory of source files makes documentation more readable (i.e., more reviewable) by more people.
–
mouvicielFeb 5 '13 at 8:40

2

Well, no, it does not. How are you going to notice in the .pdf, that the code actually does something subtly different than the description says?
–
Jan HudecFeb 5 '13 at 8:45

1

Maybe my opinion is biased by my domain, space critical software where everything is reviewed, controlled, verified, tested twice or three or four times. Automatic generation of documentation does not suppress inconsistencies but it helps reducing them.
–
mouvicielFeb 5 '13 at 8:52

1

+1 for civility in the face of hostile comments.
–
LarsHFeb 5 '13 at 14:49

I'm going to state what most of the answers and comments hint at: you probably need to figure out the real issue here rather than trying to push your perceived solution through.

You are motivated to see comments in his code; why? You gave a reason; why is that reason so important to you? He is more motivated to do something else instead; why? He'll give a reason; why is that reason so important to him? Repeat this until you arrive at the level where the conflict really arises, and try to find a solution there that both of you can live with. I'll bet it has very little to do with commenting.

Love the code review answers, but perhaps my process will help a little too.

I love comments, but I almost never add them into the code on the first pass. Maybe it's just my style but I'll hit the same section of code 3 to 5 times during development (refactoring, writing tests, etc).

Whenever I get slightly confused or whenever someone asks me a question about a section of code I attempt to fix it so that it makes sense.

This can be as simple as adding a commento removing a confusing set of operations into their own function or it can trigger a larger refactor like extracting a new object.

I suggest that you encourage everyone in the group to "own" that their code is readable to others--this means that every time someone asks you a question about your code, you commit to making a change--or better yet pair with that person to make the change right then!

Seriously consider pushing for this as part of your "Team Contract" (And definitly create a contract if you don't have one)--that way everyone has agreed on it and you have it up on a wall somewhere so that there isn't any question about what you've agreed to do.

Maybe this guy needs to be given an appreciation of good coding discipline, and why it's important for other people to be able to understand code he's written.

I've worked on some truly awful codebases in my career, ones where the code was so badly organized, variable names were so poor, comments so bad or non existent, that the codebase harmed my productivity. You can't work to fix or improve a codebase you don't understand, and if it's written in a way that's impenetrable to newcomers then they'll spend more time trying to understand it than actually working on it.

There's no better teacher than harsh experience!

Every codebase has some horrible bits lurking in it, parts of the system nobody wants to touch because they're afraid of breaking something, or they can't do any meaningful work on because whoever wrote the code has long-departed and taken their understanding of the code with them. If that code is uncommented and not self-documenting then it only makes matters worse.

I suggest you find the bit of your codebase that's like that, and give your troublesome coder responsibility for it. Give him ownership of it, make it his responsibility, let him learn the true pain of working on code that can't be maintained because it's not well documented or impossible to understand in a short space of time. After a few months working on it, I'm sure he'll start to come around.

I just barely avoided the -1 button on this. Most of the code I write has very few comments. I don't think I've had people complain that it isn't understandable in the last several years at least. With very few exceptions, if the code needs comments to be understood, then it doesn't need comments, it needs improvement for clarity. (Of course, you have to assume basic understanding of the language's syntax. Things like, in C++, don't go out of your way simply to avoid using reinterpret_cast<>() because people may find it confusing; in C#, if ?? does what you need, use it; etc.)
–
Michael KjörlingFeb 5 '13 at 10:37

2

@MichaelKjörling: It may depend greatly on what kind of code you're writing. If your code depends on uncommonly-known characteristics of a language or an API, or you did something in a counter-intuitive way in order to avoid an obscure bug that took you hours to discover, it would be a lot more effective to comment about it (possibly including a link to an article) than to try to make the code "clear" about this background information w/o comments.
–
LarsHFeb 5 '13 at 14:41

Does this programmer do some code maintenance. If not, he should: check for any disliked project you have around and assign its maintenance to him.

Usually those are the badly documented projects where you lose hours trying to understand what is going on to correct what could have been easy to correct.
If this kind of experience does not make him want up to date, correct and useful documentation nothing will.

In one of my past projects were missing dozens of comments (algorithm, results or some basic JavaDoc), so I just decided to make 130 issues for him, e-mail notification about each of issue every 4days. After 3weeks he had 280 issues, then he decided to write comments.

To supplement the answers here, I might add "If you want it done right you have to do it yourself."

I don't mean becoming "chief code commenter", I mean becoming a role model in demonstrating what you would like this other developer to do. They say showing is more effective than telling. If you can demonstrate the benefit of quality comments, or even mentor this other developer (to the extent that he's willing) you may find more success in code comment adoption.

Similarly, at home there are some household chores I don't care to do. However those same chores happen to be my wife's "pet peeve" chores... chores that must be done for her to be happy. The same situation applies vice versa. I think you may have to accept that this other developer has different priorities than you, and will not agree with you on everything. The solution that my wife and I have found is that for those "pet peeve" chores we just have to do them ourselves, even if it means doing a little more work on our own.