185

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?

samthebrand
  • 368
  • 2
  • 12
  • 27
Md Mahbubur Rahman
  • 4,747
  • 5
  • 32
  • 38
  • 2
    Are they employees? – Austin Henley Feb 05 '13 at 06:18
  • @AustinHenley Yes, He is employee and I am employee too. – Md Mahbubur Rahman Feb 05 '13 at 06:20
  • 1
    Is his code self documenting? how much commenting is required? – Karthik T Feb 05 '13 at 06:23
  • @KarthikT, No, his code is not Self Documenting. – Md Mahbubur Rahman Feb 05 '13 at 06:25
  • 1
    I've seen practises where people only comment all the mistakes. (If you write 2 pages of comments, you made huge mistake :) => the best code has no comments at all. – tp1 Feb 05 '13 at 06:28
  • 2
    My lead made documentation one of the Acceptance Criteria. Pairing and Code Review can help in this area too. What is your role there ? Is this something you are trying to make him do or is it company policy ? – ShaggyInjun Feb 05 '13 at 06:31
  • @tp1, Yes, I agree with you. I need minimal comments as other can understand his code. – Md Mahbubur Rahman Feb 05 '13 at 06:31
  • 110
    Commenting for comments sake does not make the code better. If the code is understandable (including why) without comments then fine otherwise comment. – Martin York Feb 05 '13 at 06:37
  • 2
    If the code is understandable without comments, that means the code doesn't invent anything. There is no intellectual property in it besides basic copyright. Suppose nobody knew the Fast Fourier Transform, and you happened to invent it in your block of code. Would it be obvious to everyone that it is performing a discrete cosine transform, in a different way? Or would it need comments? (Not to mention references to the paper you would have to write ...) – Kaz Feb 05 '13 at 09:22
  • 63
    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 ... – Kaz Feb 05 '13 at 09:28
  • 12
    @Kaz Sarcasm (I hope) does not translate well to text. – deworde Feb 05 '13 at 10:23
  • @Kaz I really hope it was Sarcasm cause otherwise its pretty bold statements you wrote... – artjom Feb 05 '13 at 10:26
  • 10
    @deworde & artjom - yes, that's sarcasm. no, it doesn't come across as cleanly as it could, but it's clearly sarcasm. –  Feb 05 '13 at 11:45
  • 4
    "why it breaks in mysterious ways if they make experimental changes": Most of the code tends to break if you make _experimental_ changes (i.e. without really understanding what it does). – Giorgio Feb 05 '13 at 12:29
  • 2
    I wonder - is somebody doing code reviews for that particular programmer? – Sulthan Feb 05 '13 at 12:50
  • 17
    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.. – Anirudha Feb 05 '13 at 13:28
  • 10
    Have you considered an alternate hypothesis, that the code is perfectly understandable to him AND TO ANYONE ELSE WITH HIS WIZARD LEVEL OF SOPHISTICATION, but not to people who have barely achieved Journeyman or are still Apprentices? I have seen cases like this, in specialized real-time image-processing applications, and, as it turned out, it was absolutely necessary to train up to Wizard to be able to work on the code, NOT because it was undocumented, but because the problem domain was inherently hard. By the time I understood the domain, his code WAS self-documenting (and CLEAN!). – John R. Strohm Feb 05 '13 at 22:29
  • Here's a perhaps less popular perspective on comments: http://anticommentist.org – gregghz Feb 05 '13 at 23:41
  • 1
    You should read [what Jeff Atwood has to say on this subject](http://www.codinghorror.com/blog/2008/07/coding-without-comments.html). – BЈовић Feb 07 '13 at 08:03
  • 3
    I feel like this questions should be "How can I deal with a team member who doesn't (do something we all recognize as good practice)?" – Mitch Feb 08 '13 at 19:02
  • 1
    The question of comments should be linked to why the code is doing what it is doing and not what it is doing. Because ime quite a lot of coders are lazy, they go for the minimum they can get away with without actually providing adding value. It's entirely possible that self documenting code exists but it is heavily dependent on a perfect design which in the real world rarely exists and when modifications are required, game over. Document the why, not the how. – temptar Feb 08 '13 at 20:22
  • @temptar A good coder is lazy, but *they go for the minimum they can get away with without providing adding value*? That's quite an offensive generalization to put on a site full of coders. A good coder is lazy because he's looking to reduce *everyone*'s effort, not just his own. He's searching for generalizations that solve problems in a lasting way. – kojiro Feb 09 '13 at 20:33
  • If he's the only one of the team who refuse to comment his code yes, you've a problem. And it's not about comments, it's about teamwork. If you and your colleagues have an hint that he is trying to gain power within your organization denying you all information you have to stop him asap or he'll ruin your workplace. – chirale Feb 09 '13 at 21:17
  • You should provide a few more details: how long are these functions that he is not commenting? And does each function have a comment (javadoc/pydoc/phpdoc/jsdoc/etc.)? Or is he literally writing *zero* comments? If it really is the latter, and he won't agree to improve, then fire him. Code that can't be maintained is of less value then code that can be maintained, and if it's bad enough, it may even be a net liability -- you're paying someone to actually erode the financial value of your product. – Mark E. Haase Feb 17 '13 at 13:16
  • Send them to azkaban and let them have it!, kidding aside. I've met a lot of people who does not comment their code, I explained to them and made them realize how important it is to comment their code since they are not the only ones who are working on a given project, and told them "What if you are the one reading a undocumented code" a little reverse psychology does the trick. – KyelJmD Feb 23 '13 at 07:27
  • I'd say "give him a taste of his own medicine", task him with fixing/debugging/extending a piece of code some other non-commenting predecessor has left... – SF. Feb 26 '13 at 10:40
  • 1
    Implement StyleCop on your projects and set specific rules for commenting code. That will force him to start thinking about code quality. – Haris Feb 27 '13 at 11:49
  • A 2 hour call on the midnight before the due date asking to explain the code should convince him. – jkd Jun 08 '15 at 13:35
  • see also: [“Comments are a code smell”](http://softwareengineering.stackexchange.com/q/1/31260) – gnat Nov 08 '16 at 07:15

23 Answers23

430

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.

samthebrand
  • 368
  • 2
  • 12
  • 27
tdammers
  • 52,406
  • 14
  • 106
  • 154
  • 269
    +1 for "don't complain about missing comments: complain about unreadable code." – Md Mahbubur Rahman Feb 05 '13 at 06:39
  • 4
    What if the answer to any question about code is along the lines of "What have you done to understand it?" – Saul Feb 05 '13 at 09:58
  • 40
    +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?" – deworde Feb 05 '13 at 10:03
  • 19
    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 05 '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... – deworde Feb 05 '13 at 10:13
  • @RobP. Also, the correct way to solve the issue of a non-tech manager not being clear on how knowledgeable you are is spending more time talking to them (Lunch or One-to-Ones, whatever works) – deworde Feb 05 '13 at 10:16
  • 2
    @Saul In that case, reply "I've read it and could not understand it all. I should not have to run it to know what it does." – MPelletier Feb 05 '13 at 10:53
  • +1 for slapping down "It's best practice". I've banned that phrase. – Ian Feb 05 '13 at 12:09
  • @MPelletier - Last time I heard, the customary reply to that was "Then read it again and again until you do understand". Some developers just are not interested in explaining their code unless they really have to. – Saul Feb 05 '13 at 13:21
  • @Saul - that's a stupid question. If you have to make a special effort to "do something" to read it, that's a problem. Expecting to read things "at a glance" is often unreasonable, but it shouldn't be quicker and easier to go and ask someone than to read the code. There's a possible exemption for common knowledge, but even that should be documented somewhere for newbies and to make sure everyone has the same "common" knowledge. Of course you should express it more tactfully than my "that's a stupid question". –  Feb 05 '13 at 13:22
  • 1
    @Saul, I've been there too. It's hard to change people. Keep at it. Another approach, after about 6 months, your old code doesn't even look familiar. It's become someone elses. Let him re-read some of his old stuff from a while ago. Or, you can use peer pressure: "I can understand everyone else's code at a glance." At some point, you (and he) have to understand that you're paid to create software. Time is precious. Optimize time developing by leaving no ambiguities. – MPelletier Feb 05 '13 at 13:45
  • 2
    @Steve314 - In the ideal world, yes, but in practice that is rarely so. Reading code is always harder than writing it, especially if the author is someone else. Add in the factors of preference, skill and experience and you get very different opinions whether a particular code unit is easy to understand or not. That is the reason why I am a bit sceptical in setting the standard to "easy to understand". – Saul Feb 05 '13 at 13:48
  • 1
    For one of my projects I simply stopped writing what I considered "meaningless comments." The benchmark for this was simple: what good are these comments if even I who wrote them don't find them useful. So I stopped writing @meta (ie. param) comments and focused only on writing good examples and paragraphs as well making sure method variables are clear by themselves, several words if need be, made sure to add comments to what I considered "biased or opinionated implementation" and also made sure to write hints, such as a comment after ever "else." Everywhere else, my variables are my comments. – srcspider Feb 05 '13 at 14:00
  • 1
    +1 for leaving room for the possibility that the offending person has a functioning brain. – Phil Feb 05 '13 at 14:22
  • 1
    This has some merit, but it means that whenever team member X needs to read code, which happens to have been written by team member Y, there's a big time lag and delays while we discover that team member Y did not document his significant assumptions or questionable logic, or while Y is unavailable for comment. That kills X's productivity. Moreover, if much time has passed, even Y will be unable to recall why he wrote a line of code the way he did, or what he learned from API documentation or a PSE post that convinced him to do it this way and not that. – LarsH Feb 05 '13 at 14:35
  • +1 but I think this doesn't apply to API doc which is very important because you need to have well documented what the function/method does and return. – Alfredo Osorio Feb 05 '13 at 14:50
  • If you'd have 2 such colleagues, you could make them work together and try to understand each other's code. This would make them both realize the necessity of writing readable code. – Petr Feb 06 '13 at 08:48
  • +1 for "don't complain, just keep asking questions about the code" – daviewales Feb 06 '13 at 15:38
  • It seems a very good idea, but has someone seen this actually work? – Dr. Hans-Peter Störr Feb 12 '13 at 11:52
  • 2
    @hstoerr: yes. All the time. – tdammers Feb 12 '13 at 12:41
  • I can figure out anyone's code. Poorly commented code wastes my time; it wastes time in development, it wastes time in maintenance, it wastes time fixing bugs, and most unforgivably, it wastes time fixing critical exploits. That pisses me off. It's irresponsible. – lordcheeto Feb 16 '13 at 19:25
  • 1
    "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." I guess you never worked on a project that was maintained and changed much over years. The best answer you get after a month is "I'm not sure, but I think it was because..." and after a year or so: "What?! I didn't wrote that! Oh... So it says I did in the SVN log... well...". – Nux Mar 01 '13 at 02:43
  • Toobs, I miss you – Robert Sirre May 29 '15 at 15:20
114

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.

Doc Brown
  • 199,015
  • 33
  • 367
  • 565
  • 5
    +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 Hoffa Feb 05 '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 Brown Feb 18 '13 at 13:25
27

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)

Earlz
  • 22,658
  • 7
  • 46
  • 60
  • 2
    +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. – Dunk Feb 06 '13 at 14:16
  • +1 Also surprised code/peer reviews are so low down the answers. Implementing team level code-reviews (so as not to pick on an individual) could help solve the problem (and maybe others you don't even know you have:). At the extreme you could implement a no-solo-push policy whereby you are not allowed to push unless your changes have been reviewed by another team member. – Chris Lee Sep 17 '13 at 19:32
  • @ChrisLee at my company code review policies aren't enforced technically, but there is a policy that before a story can be marked as being Ready For Test, it must be code reviewed, no matter who did the development work. It's quite interesting having to code review when the CTO makes a check in though lol – Earlz Sep 17 '13 at 21:21
18

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.

Frank
  • 14,407
  • 3
  • 41
  • 66
  • +1 for discussing the actual profits from comments. Comments are meant to add value to the source code. – Sparky Feb 06 '13 at 13:16
  • 1
    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. – Dunk Feb 06 '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. – bharal Feb 06 '13 at 16:45
  • While comments in code would not be necessary, there should be at least the method description, such as Javadoc – Danubian Sailor Feb 08 '13 at 08:59
  • 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. – GordonM Feb 17 '13 at 11:48
  • Even if you use ridiculously long variable names the code itself won't tell you why something was done. E.g. based on what kind of requirements ("using function X because Y is much faster in Chrome 9" - tells you to test against Chrome if you refactor the code) or which requirements the code was made like so ("for a client no. 54321, see bug #1234; it's stupid, but he paid $10.000 for it so don't break it" - it might sound funny, but this kind of comments let you avoid a lot of serious real-world problems and fast re-releases). – Nux Mar 01 '13 at 02:55
9

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…

  1. 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.)
  2. 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.)
  3. 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.

kojiro
  • 2,105
  • 1
  • 15
  • 29
  • 3
    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. – GordonM Feb 17 '13 at 11:50
  • @GordonM Do you think it would be better *not* to tell an employee when his behavior is inappropriate, and what the consequences of continued inappropriate behavior would be? – kojiro Mar 02 '13 at 20:38
  • Not saying anything at all isn't a good idea obviously, but threatening people is just going to foster a climate of fear, especially over a relative minor thing such as commenting style. If you explain to him reasonably why the team considers commenting important that's fine. But I know if someone threatened me with the sack over something relatively minor I'd be more inclined to just start looking for another job instead. – GordonM Mar 03 '13 at 08:46
  • @GordonM I actually take exception to the implication that what I said was threatening, but anyway, I fixed it. – kojiro Sep 14 '13 at 13:01
8

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.

Danny Tuppeny
  • 896
  • 6
  • 13
4

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).

  • You can write code that does not need comments only for fun. This might indeed be a great exercise but not if you need come back to the code and can't really change anything because you won't know why this function works as it does maybe there was some client that wanted it like that. Of course you might be in that maybe 1% of project that is documented and reasoned outside the project, but even then there are decisions you make during coding which do not get pushed back to the documentation. And frankly... Who reads documentation that is not in the code. Certainly not programmers ;-P. – Nux Mar 01 '13 at 03:12
  • 1
    A good engineer cares about the whole system (incl. non-codegenerated documentation) - but here we, of course, mind coding in general.. My point is that not having identifiers in the code called *foo*, *bar*, *tmpSomething2* and *IamJustTooSmartAssToCare* already improves the situation and reduces the overall need to explain what the code is and what it does. Code should be written with "thinking mode on" like a well-designed API that is read, understood, reused and maintained by humans. Too many comments in code that is otherwise difficult to understand is a very bad sign! – Yauhen Yakimovich Mar 01 '13 at 15:02
  • BTW programming/encoding any type of domain specific logic in form of a HACK or a "temporary" bug-fix is in fact producing "weird HACKs" - as soon as you have a lot of them squeezed in inside the blackbox - expect them to fail and fire back. This can be justified by deadlines in the "real world" projects,etc. but in reality it is just cheap software that requires remodelling of domain logic (or maybe finding a new job). – Yauhen Yakimovich Mar 01 '13 at 15:13
  • I agree that readability is important, what I disagree is that you seem to say "if you make readability a priority you won't need comments". That is simply not true. Been there done that. Reasoning what you do doesn't just come from naming variables in a way that makes sens. Do that of course, but also add reason in comments (even if it is in a form of a bug/requirement/story number in some external system). That's what I'm saying. – Nux Mar 04 '13 at 12:33
  • "if you make readability a priority you won't need comments" - yes this exactly what I am saying (and I am aware this does not seem easy to achieve). BTW Do you have situations when maintaining complete commit (version control) history is not enough to reflect on "bug/requirement/story number"? I have been practicing rather long commits - works for me and allows to keep code empty from development history..makes it less organically grown. – Yauhen Yakimovich Mar 04 '13 at 13:53
  • I have a real world example for you: due to failure to care ;-) (of one of our programmers) we lost commit history of pre-SVN era (lost in CVS to SVN translation). **Also** SVN log is in a similar way external as other docs - easy to get lost unless you use SVN to bug requests automation and will almost certainly be lost when you change your issue tracking system. **Also** it will be impossible or close to impossible to keep tracking of function-to-request connection if you move functions around (e.g. refactoring to split on class into 2-3 classes - also a real world example). – Nux Mar 05 '13 at 14:26
  • Ok, I guess **git** (heavy submoduling and branching - branch per bug) is just too complicate to change the established process on the project you mind. But you must see that this is also a bad sign for me. Just for a sake of fairness let me admit that there are indeed a number of examples that do make one's code better by adding comments (in direction of http://en.wikipedia.org/wiki/Literate_programming) But somehow when OP asks a question like this most likely the code is just garbage. – Yauhen Yakimovich Mar 05 '13 at 14:57
3

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.

Pete
  • 8,916
  • 3
  • 41
  • 53
  • Pair Programming is an excellent Idea, it gives another programmer insight into the development of the code so they know what is going on, making two people accountable for the code. it also gives the chance for one of the two to say that something should have a comment because it is out of the ordinary or something that someone else might change because it looks like ... "a memory leak", "bad coding", etc. some things need commenting so someone else in the future doesn't undo something because it doesn't look right. – Malachi Feb 05 '13 at 16:20
3

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?

// this method returns the sum of 'a' and 'b'
public int GetHash(int a, int b)
{
    //the calculation of the hash
    int result = a*b;
}

(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!

samthebrand
  • 368
  • 2
  • 12
  • 27
Paul
  • 394
  • 2
  • 8
  • 4
    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? – jmk Feb 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. – DBlackborough Feb 17 '13 at 00: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. – xaxxon Feb 17 '13 at 02:32
  • 4
    @xaxxon Not to mention that apples even if that person might be you. – fluffy Feb 17 '13 at 03:00
  • Silly. If the comments are wrong, then the person writing them should be held accountable. That's inexcusable. The purpose of comments is to explain *what*, not *how*. Your trivial example is trivial. Some real function will be more complicated and justifies at least one or two sentences about what it's there for and how it should be used. – Mark E. Haase Feb 17 '13 at 13:20
  • @jmk I was not saying "never" use comments, I suggested to get rid of all those, which one can. If comment can be removed via renaming/refactoring - that's the right way to go - those comments must not remain. – Paul Feb 18 '13 at 23:34
  • @mehaase I don't find it to be helpful to hold anyone accountable for the issues that could have been avoided in the first place. I do agree that there are complex algorithms etc that need explanation, but those are very rear. If method size is 5-3 lines of code and it's "SRP-complaint" - I can hardly find a reason to add a comment to it, since its name will state what is the only thing this method is meant for. – Paul Feb 18 '13 at 23:45
  • @G3D I will disagree here, commenting on "where it will be used" is one of the wrong thing to do. One should never comment the intended usage - it does not guarantee it will not change and when it changes - people will 95% forget to update/remove the comment (hey, why would I need to touch this class if I just used it or its property in some other way =)) which will lead to issues later. – Paul Feb 19 '13 at 00:10
  • @Paul, different issue, developers not updating comments is not an excuse to not add them, educate the developers, don't just give up. – DBlackborough Feb 20 '13 at 03:04
  • @Paul I don't advocate adding comments where none are required, either; we all agree that the "add a and b" kind of comment is useless. But that's not an argument against comments, it's an argument against *bad* comments. – jmk Feb 20 '13 at 18:42
  • 3
    @mehaase - Not what, not how, but **why** is the most important reason to add comments to code. – Henk Langeveld Feb 26 '13 at 21:38
1

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?

LJ2
  • 111
  • 3
  • When a room full of people start laughing at your unreadable code, you'll start doing a better job of coding and commenting. :) I am a big advocate of code reviews. – Evik James Feb 05 '13 at 16:15
  • 1
    Having people laugh at code in front of other colleagues is not the way to do :-\ – Danny Tuppeny Feb 05 '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 Brown Feb 18 '13 at 13:10
1

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.

Brendan
  • 3,895
  • 21
  • 21
1

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.

samthebrand
  • 368
  • 2
  • 12
  • 27
Bill
  • 811
  • 8
  • 7
0

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.

mouviciel
  • 15,473
  • 1
  • 37
  • 64
  • 6
    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 Hudec Feb 05 '13 at 08: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. – mouviciel Feb 05 '13 at 08: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 Hudec Feb 05 '13 at 08: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. – mouviciel Feb 05 '13 at 08:52
  • Yes, you are strongly biased. In domains like that it makes sense, in most unit tests are sufficient for QA and documenting every last function would be waste of time. – Jan Hudec Feb 05 '13 at 09:01
  • The problem with that approach is that you easily end up with "Gets or sets the `Foo`" style documentation which is worse than no documentation at all. – CodesInChaos Feb 05 '13 at 14:58
0

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

   var str1:String="" //not uderstandable
   var strSearchPattern:String="" //uderstandable
M.S.Nayak
  • 109
  • 2
0

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.

reinierpost
  • 587
  • 6
  • 8
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.

Bill K
  • 2,699
  • 18
  • 18
0

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.

GordonM
  • 6,295
  • 1
  • 21
  • 30
-1

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.

  • 12
    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.) – user Feb 05 '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. – LarsH Feb 05 '13 at 14:41
  • @MichaelKjörling: I'm especially motivated to say that today because I've been wrestling for the past month with a deep GIS API. The API's facilities are complex, and not very thoroughly documented. We are constantly running into surprises, some of which set us back days at a time. To expect someone else (or me in 6 months) to have to rediscover those nuggets in order to work effectively with our code would be a huge waste of that person's time. And those secrets generally can't be documented by non-comment "improvement for clarity". – LarsH Feb 05 '13 at 14:48
  • @LarsH That would probably qualify as one of those "very few exceptions" that I mentioned in my comment. I'm not against commenting where it actually *adds value*; but it's not the amount of comments that makes code easy or difficult to read. That said, with an API, I'd be more inclined to document those quirks elsewhere; say, in a wiki or similar. Maybe also add a link to the relevant page next to each usage. That way, you don't have to go looking for some other place that uses that particular feature of the API whenever the code doesn't work quite like you expect on the first attempt. – user Feb 06 '13 at 08:16
  • @MichaelKjörling: agreed in general. Whether these exceptions are rare or not depends on the domain you're programming for, and the API's you have to use. Links/references are good for notes that apply generally, not just to the current situation. Nobody wants a dissertation in the code itself. – LarsH Feb 06 '13 at 15:01
-1

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.

Arkh
  • 591
  • 3
  • 8
  • 1
    This approach is more likly to make the programmer quit rather than training them in the proper way of doing things. – Martin Brown Feb 18 '13 at 13:11
-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.

agilob
  • 101
  • 1
  • 3
-1

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:

/* Must instantiate clsUser before trying to encrypt a password because the code to 
   encrypt passwords only uses strong encryption if that module is loaded. */

A bad example:

/* instantiate clsUser */

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.

Jonathan
  • 207
  • 2
  • 5
-2

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.

sourcenouveau
  • 6,460
  • 4
  • 29
  • 44
  • 1
    I'd argue that showing cleaner code/refactoring their code to be more readable demonstrates a greater change than putting gobs of comments into the code. – Makoto Feb 17 '13 at 17:15
  • Can anyone explain to me what they don't like about my idea...? – sourcenouveau May 14 '13 at 02:30
-6

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.

peter
  • 101
  • 2
  • 11
    "Auto comment"? So *that's* where all those "increment i by 1" comments are coming from? Which IDE does this (so I can avoid jobs where it's being used)? – user Feb 05 '13 at 12:14
  • I tried to edit this into something readable, but I'm not sure whether the word *first* should have a comma before it or after it. Is the phrase *make comments first* or *first tell in each method*? – TRiG Feb 05 '13 at 15:31