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
- Refine your program’s loops, logic, and variables to reduce complexity and confusion
- 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).
How can I deal with a team member who dislikes making comments in code?
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?
29
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.
23
I have met lots of devs who had trouble in writing self-documenting code or helpful comments. These kinds of people often lack enough self-discipline or experience to do it right.
What never works is, “telling them to add more comments”. This will increase neither their self-discipline or experience. IMHO the only thing that might work is to make frequent code-reviews & refactoring sessions. When a dev has completed a task, allow him/her to explain any parts of the code you don’t understand. Immediately refactor or document the code in such a way that both of you will understand 6 months later.
Do this over a period of a few months, at least twice a week. If you are lucky enough, the other devs will learn through these sessions so that you can reduce the review frequency.
2
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)
3
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.
6
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…
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.
4
Get code review software, and use it well.
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.
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)
every line of code
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).
7
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.
1
First of all, I would suggest you re-address your approach about the comments.
If they are documentation comments at the API level (exposed later to public), then this developer simply isn’t doing his job. But for all other comments, be careful.
In most of the cases I encounter them, comments are evil. I would recommend reading the code comments chapter of “Clean code” by Robert Martin to get a good understanding why.
Comments hurt your code in several ways:
1) They are hard to maintain. You’ll have to put in extra work when refactoring; if you change the logic described in the comment, you need to edit the comment too.
2) They often lie. You cannot trust comments and must read the code instead. Which raises the question: why would you need the comments at all?
(The hash is not the sum but the product.)
3) Comments clutter the code, and very rarely add any value.
My solution: Instead of adding more comments, try to get rid of them at all!
11
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:
Is code reviewing good practice?
3
Considering the often extreme views on commenting, I hesitate to weigh in. That being said…
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.
Many projects require code documentation: interface document, design document, …
Some projects require that such documentation shall be put in code comments and extracted with tools like Doxygen or Sphinx or Javadoc, so that code and documentation keep more consistent.
That way, developers are required to write useful comments in code and this duty is integrated in project planning.
6
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.
If you follow good coding standard, there will be a minimum number of comments required.
naming conventions are important. Method names and variable names should describe their role..
My TL suggests me to use less comments. he wants my code should understandable and self descriptive.
simple example:
variable name for string type which used for search pattern
0
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.
Give him some one else code without comments and ask him to understand the code. May be he understand the importance of proper comments then.
5
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.
1
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.
Comments have one purpose, and one purpose only:
Why does this code do this thing?
If a comment does not explain why something is the way it is, then it should be removed. Useless comments which clutter up the code are less than useless, they are actively harmful.
I have a habit of making my comments the most obvious thing in my IDE. They are highlighted with white text on a green background. The really draw your attention.
This is because the code explains what something is doing, and the comments are for why it is doing it. I can’t emphasise this enough.
A good example of a comment:
A bad example:
If you are using comments as “sections” of code: Chop your mammoth method up into smaller, useful named functions, and remove the comments.
If you are saying what you are doing on the next line: Make the code self-explanitory and remove the comment.
If you are using comments as warning messages: Make sure you say why.
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.
2
Simple: if the employee does not make comments, tell him to press
shift+alt+j
for auto comment in each method simultaneously with entering the code. please do code revision for avoid these problems.2
Filed under: softwareengineering - @ 21:28
Thẻ: comments, team, teamwork
« R script (mailR) all files from folder as attachment ⇐ More Pages ⇒ How to download Visual Studio Community Edition 2015 »