Slashdot Mirror


How To Get Developers To Document Code

snydeq writes "Poorly documented code? Chances are the problem lies not in your programmers, but in your process, writes Fatal Exception's Neil McAllister. 'Unfortunately, too few developers seem to do a good job of documenting their code. Encouraging them to start can be a difficult challenge — but not an impossible one,' McAllister writes, adding that to establish a culture of documentation managers should favor the carrot before the stick. 'Like most people, programmers respond better to incentives than to mandates. Simple praise can go a long way, but managers may find other ways to reward developers. Are your developers occasionally on-call for weekend support duties or late-night update deployments? Consider giving them a break if they volunteer to pick up some extra documentation burden. Of course, financial incentives work, too.'"

89 of 545 comments (clear)

  1. How to poke a dead body by alphatel · · Score: 2, Insightful

    It's called doing your job.

    --
    When the foot seeks the place of the head, the line is crossed. Know your place. Keep your place. Be a shoe.
    1. Re:How to poke a dead body by rufty_tufty · · Score: 5, Interesting

      True but like it or not people don't do it. You can bitch that people should do it, but when they don't what then? You could fire them, but IME some of the people who write the best code by other metrics (reliability, bugs fixed, or just taking on a task no-one wants) are poor at documenting it themselves.
      Do you fire people for not documenting code, discipline them? Is it worth fighting the battle if you just need to get the product out/fix the current problems/develop the next thing.
      IME code quality always comes back to bite you, if you write bad code/undocumented then soon enough it will come back and bite you yourself when you come back to maintain/modify. If I don't provide documentation to others then I end up with more support requests so it's worth me doing that balancing act, it's not management's judgement call to make.
      As for dealing with other people undocumented code, that's just a skill you need to have as an engineer, like being fluent in multiple languages many of which won't be your choice. You think I want this tool chain to be written in TCL? Should I then port it to my favourite language (e.g. perl) what if the next poerson to support it prefers python? It's just part of engineering that everyone else's code will look rubbish and undocumented to you. Even when it is documented you'll then think the documentation is overkill.
      Yes it's rubbish, yes TFA makes some suggestions, some might work, some might not, but you can't just say it's your job to document and walk off, in real life we have to actually deal with problems and the reality that it doesn't happen as it should.

      --
      "The weirdest thing about a mind, is that every answer that you find, is the basis of a brand new cliche" -
    2. Re:How to poke a dead body by Anonymous Coward · · Score: 2, Informative

      It's called doing your job.

      And if your job does't measure your comments as part of its "productivity metric"? Like companies that use 'Klocs' to see how much 'work' you've done?

      Commnets aren't included when counting. So, it's quite clear that commenting code isn't part of the job.

    3. Re:How to poke a dead body by Moryath · · Score: 5, Insightful

      Indeed. The rise of "metrics for job performance" has caused a lot of pain for many sectors of IT.

      Judging your programmers by "lines of code written"? Great. They'll write a solution with as many redundant lines of code as possible. They won't comment, because commenting doesn't count. Bugfixes will generally involve patch code that means more lines, rather than cleaning up the code itself.

      Judging your IT support by "number of tickets cleared"? Great, you get just what people expect out of those @##$@#$ crapass "phone lines" that bank out of India or Malaysia; they'll do anything to get you off the phone as fast as possible and mark your issue "resolved", whether it is or not. Your in-house guys will have to triage: do we handle 5 "my flash isn't working and I can't watch youtube on company time" issues, or do we handle the issue for one person that's going to take ALL MORNING to resolve but since it's only one ticket, will red-flag us as "not getting enough done" according to The Almighty Metrics.

      The Retardicans have started to try to put this into play in the education field, too - teachers' pay will now be dependent on the grades the kids get and their performance on certain tests. You can - as my mother has - put in 70 hour workweeks, staying after every day to tutor kids who have problems, seeking out specialists to help the couple of kids who actually may wind up diagnosed with a learning disability (example: one in particular can write at an 8th-grade level but can't seem to wrap his head around long division after 6 months of trying), trying to figure out what's with the others only to find out come P/T conference night that they aren't learning because they've internalized their parents' opinion of school as glorified daycare and therefore just don't want to pay attention - but the parents DEMAND that they be passed on to the next grade because it'll hurt Little Dumbass McAsswipe Junior's "self esteem" to be held back a grade. You can do all that and it WON'T MATTER, because the kids with learning disabilities won't be diagnosed for another 4 years, and there are enough Dumbass McAsswipe Juniors in the class to pull "the metric" down.

    4. Re:How to poke a dead body by Eraesr · · Score: 5, Insightful

      Most of the time the problem doesn't lie with the developer. The developer who actively refuses to document is rare. In my experience, the real problem lies in managers not taking documentation seriously. It is caused by developers being under the stress of deadlines with a manager that really needs this piece of software to be finished yesterday. Managers just don't schedule in any time for documentation.

      Another issue the article touches (and I really shouldn't have to say this because of course you have already thoroughly read the entire article. Twice) is that there's the question of when to start documenting, because software and APIs are often subject to change all the time, not in the least because managers keep asking for new or different features.

      Personally, I often enjoy writing technical documentation. If I've written good portions of an API or framework that I'm particularly fond of, because it's all done oh-so-clever, you know, I enjoy committing the inner workings to paper to explain to my colleagues how it works and how it's supposed to be used. Unfortunately, like I said before, there often isn't any time to write good documentation and that's a real shame.

    5. Re:How to poke a dead body by LordLucless · · Score: 5, Insightful

      I totally agree.

      You want to know how to make developers document? Give them time to do it. Do not give them another project until the one they've just deployed is documented. Factor in time for documentation when quoting for the time taken to complete a project, and don't treat documentation time as "pad" time that can be consumed by the project when it overruns its overly-optimistic deadline.

      Treat documentation as as valuable as code, and it will get done.

      --
      Just because you're paranoid doesn't mean there isn't an invisible demon about to eat your face
    6. Re:How to poke a dead body by Anonymous Coward · · Score: 4, Interesting

      At my company our process now is built around Design By Contract. Since C++ doesn't have all of the DBC concepts built in as language features, we use comments and macros to define the contract for each class, method or function. The comments include pre conditions, post conditions and the testable restrictions on input parameters and return results (i.e. param x must be between 1 and 10, possible return results are -1,0 or 1). These comments are implemented by macros that do the actual verification.

      We then do rigorous code review--if your methods aren't commented and the macros don't match the comments, your code is rejected. Therefore all of the code in our repository is commented and the quality of the comments are exceptionally good. What's more, all of our code is inherently testable. We also don't mark a module "done" until it has 100% test coverage from our automated test suite.

      So far in the 18 months we've been doing this process, no one has complained of the "burden" of doing the process and everyone has a much clearer understanding of our system design now. And everyone has had at least once experience where the DBC methodology has found what would otherwise have been difficult bugs to find.

      So where we work, comments are part of the code and cannot be omitted. And yes, if we had an engineer who refused to comment he would be fired.

    7. Re:How to poke a dead body by rufty_tufty · · Score: 5, Insightful

      It is their job. If they don't do it, fire them. If you can't fire them for some reason, give them crap reviews and crap tasks.

      I envy you that you work somewhere where there is an excess of perfect people that you can do this. In my experience there are some really clever people out there who have some personality flaws, and there are lots of people who stick to the rules and are quite average. Personally I'd rather try and work with flawed brilliant people and accept undocumented but efficient, quick, timely code than get a monkey who follows the rules and produces acceptable code. You may not choose that trade off and that's fine we will probably never agree there...
      Now if you're telling me you can get someone who does everything brilliantly then great, but lots of great engineers are divas so whilst you can try and lead them, to give someone a poor review (when they saved your behind at the last customer demo) because that code they cooked up lacks documentation then I'm once again wondering how on earth I ended up with such an awesome job.
      FWIW I used to have a manager whose approach to people who he thought produced unmanageable/undocumented code was to stick them into a code maintenance/system integration role. It was interesting how quickly you then started complaining about other people's code and documenting both theirs and yours ;-)

      Oh, and no function should be longer than about 20 lines.

      Where's my funny mod points when I need them?

      All non-trivial code is crap and could be improved in some way

      I would say all code is crap and could be improved, the problem is where and for what purpose? Code with too much abstraction is crap, so is code with 1 line per function, so is code with too many things happening on one line, so is code that is too tied to the particular hardware, so is code that ignores what the toolkit libraries can do, so is code that is written in the wrong language for the problem you are solving, so is code that is a complete re-write, so is code that wasn't profiled properly. etc
      Any blanket rule you can make has exceptions and while I am all for coding standards and code reviews rules are there to make you think before you break them, nothing more.

      --
      "The weirdest thing about a mind, is that every answer that you find, is the basis of a brand new cliche" -
    8. Re:How to poke a dead body by JoeMerchant · · Score: 3, Insightful

      Most of the time the problem doesn't lie with the developer. The developer who actively refuses to document is rare. In my experience, the real problem lies in managers not taking documentation seriously. It is caused by developers being under the stress of deadlines with a manager that really needs this piece of software to be finished yesterday. Managers just don't schedule in any time for documentation.

      Roll it up the chain, the Manager's manager doesn't value documentation, they value product, as does the customer. Internal documentation is something with a payoff next quarter, or more often next year. When is the last time you heard of an American business strategy that involved taking more time to do something now so that you could take less time to do something next year?

    9. Re:How to poke a dead body by JoeMerchant · · Score: 4, Interesting

      Treat documentation as as valuable as code, and it will get done.

      Who is it valuable to? When is is valuable to them? It is a complicated time-value of resources problem, and while documentation is very valuable when you need it, your time of need is a) uncertain, and b) in the future, both of which steeply discount its value (but not its cost) in the present.

      Decisions are made in the present, and if resources are tight in the present, things of potential value in the future are discounted further.

    10. Re:How to poke a dead body by SecurityGuy · · Score: 4, Insightful

      Metrics aren't bad in themselves, but bad metrics are terrible. Lines of code written is a really bad metric.

      I've seen the ticket one happen too many times. Someone will call because n people are having a problem, and ask if the hell desk person wants the info on the other people so they can get fixed, too. Nope. Have them call and open tickets. More tickets with simple, known solutions == more tickets closed quickly.

      And yeah, the same is true of teachers. Teachers *should* be judged on their effectiveness, but the way we do it is often nonsense. Don't ask me to come up with the method, the one thing I DO know is that someone with no experience in the field (me) should not be the one divining metrics to measure them. That said, we've all been through school, and some of us have put kids through school. You know some teachers are better than others, and some are really bad. We do want to find ways to encourage all of them to be better and to get the worst to go do something else. There are also fit issues between teachers and children. The teacher you found to be great for your kid might be average or bad for mine.

    11. Re:How to poke a dead body by Asic+Eng · · Score: 4, Informative

      It's a pity you didn't read the article, because you are one of the people who could benefit from it.

      What happens if your only management tool is badgering? People are going to be frustrated and bored. Their productivity will go down, the quality of their output will be reduced. You'll respond with more badgering and the situation will get worse. You can of course fire them, or they might look for more fun places to work by themselves, but then you are in the worst case scenario with heaps of undocumented code and no access to the people who understand it.

      This is basically unavoidable, because working creatively means - among other things - that you'll have to motivate yourself to do the work. It's not as easy as picking up a shovel and doing the only thing you can do with it (the work there is in the shoveling, though). Unfortunately the energy people have to motivate themselves is not unlimited. The harder a place of work makes it, the less the employees will succeed. Any basic management handbook will tell you that, any research available on the topic will tell you that - but still people prefer to manage by what they think ought to be true, instead of what's known to be true.

    12. Re:How to poke a dead body by txsable · · Score: 2

      I worked in health care IT at a hospital system for about 8 years. About 4 years after I started, the hospital administration implemented "performance metrics" across the entire system, from nurses to physical plant to...yea, IT services. Anyone want to guess what "metric" they were going to use to measure IT performance? Was it number of tickets completed? number of PCs serviced or printers replaced in a month? No..someone decided that the best metric for measuring IT was...PATIENT DISCHARGES. The number of patients (which the IT staff stayed as far from as possible) discharged by the hospital. Not only was it a statistic we had absolutely no control over, but was it totally irrelevant to our (IT services) business line. Fortunately, we had a competent VP/CIO who stood up for his IT staff and put a stop to that ludicrousness but for about two months we had to suffer from "low performance ratings" while the powers that be figured out how to measure our actual service to the hospital system.

    13. Re:How to poke a dead body by Sectoid_Dev · · Score: 3, Insightful

      If 20 lines of codes is your boundary of complexity, then programming is not for you. Breaking code into screen sized 'called once' sections adds unnecessary complexity, especially if you validate your inputs(as all good programmers should).
      Some things are just inheritently complex and the most efficient implementation might be rather abstract and not obvious at first. If you can't understand it at a first pass, the problem isn't necessarily the code.

    14. Re:How to poke a dead body by Anonymous Coward · · Score: 4, Insightful

      Unruly behavior like refusing to follow coding standards can be a sign of a problem employee that you have to let go, but it can also be a sign that all of your developers perceive your policies to be detrimental to both them and the business, and this person is the only employee you've got that cares more about the company and his craft than about his immediate bosses' sensibilities. That sort of courage could easily derive from the fact that perhaps this person is the only person who is in demand enough that he could easily find a job elsewhere. Managing by badgering, lashing and threats of firerings is a great way to lose the respect of everyone working for you. That's when suddenly productivity drops and bugs go up for no apparent reason.

      If you are a leader, and if people thought that a policy was god-awful, and then suddenly they all stop talking about it ever to you, that probably means that they have given up on your organization due to your leadership, and now they are just going in from 9-5, doing whatever you say to keep you happy, while not showing any initiative to bend your policies in the interest of the business - they are probably also looking for a different job at the same time.

      An employee who does just exactly what you say is the worst possible kind of disaster waiting to happen. You absolutely need your employees to question you. "oh, you need me to quickly finish this piece of code because minor customer X wants it now? Well, I happen to know that that same routine will have lots of bugs if not done carefully, and we are going to use it also to give to our major customer Y, to whose interests it is vital that this code work perfectly, but I won't question you by mentioning that and instead give you what you asked for." It's called malicious compliance. If you insist that employees ignore the good of the business and follow your orders to the letters instead, then watch out, you may eventually break some of them to give you what you ask for, and you won't like it.

    15. Re:How to poke a dead body by umghhh · · Score: 2

      I was convinced over the years of development, test, integration & maintenance jobs that comments are of utmost importance. When I had to write a few new modules all but myself I did indeed produced a series of descriptions in form of short module description, some comments to non obvious parts of code when after return another piece of code were to be executed when... and if... Well all this went out of window when I started to work with 5o other developers with a feeling taht all of them tried to work on the same piece of code that I was just to write. Inevitably the comments that I put for module description or TODOs were completely ignored. In a while I learned that making comments in such env. is a double. waste of time: first by writing and then by encountering my own not more valid comments that have not been updated by others. From this I learned that my comments are obviously not as desired as I thought and that I would do better to invest time in reading and analyzing code than reading comments.

    16. Re:How to poke a dead body by Tom · · Score: 4, Interesting

      Who is it valuable to?

      It's an investment into the future. If you need to pick this project up again one, two or five years down the road, and do any non-trivial changes to it, good (and that means correct, short and to the point, not extensive and theoretical) documentation will save you valuable time.

      If it's throwaway code, don't waste time and effort on documentation. If you plan to use it for some time, chances are very high it will need fixes, updates and changes, and documentation will make those a lot easier, faster and cheaper.

      Decisions are made in the present, and if resources are tight in the present, things of potential value in the future are discounted further.

      Yes. I've been trying for years to tell managers that the only reason that resources are so tight in the present is because they've been thinking that way in the past.

      --
      Assorted stuff I do sometimes: Lemuria.org
    17. Re:How to poke a dead body by Surt · · Score: 2

      It seems to me that if your only management tool is badgering, your core problem does not lie with your development team.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    18. Re:How to poke a dead body by JoeMerchant · · Score: 2

      Yes. I've been trying for years to tell managers that the only reason that resources are so tight in the present is because they've been thinking that way in the past.

      It's a valid point, but remember you are assessing with hindsight. I have actually lived through two catastrophic crashes where any effort expended for returns beyond the 3 month horizon would literally have been wasted. It is an unfortunate situation, and to be avoided if possible, but these things do happen.

      What really bothers me is when the true horizon is 3+ years, but management continues to act like it is 3 weeks.

    19. Re:How to poke a dead body by gbjbaanb · · Score: 2

      rubbish.

      You're basically saying that the creative people should be given as much free rein as they like because they won't do what they're supposed to anyway, and you'll annoy them if you try,

      Heaps of undocumented code is a problem. That the only doc is in the heads of the developer is truly undesirable because the dev who doesn't document doesn't tend to communicate in other ways when needed, and also because you're expecting that dev to be the only point of contact for all the code he's ever written. That'll annoy him when he starts getting hassled constantly for the knowledge only he holds.

      So its a management responsibility to ensure that this sorry state of affairs doesn't occur, and that his team works in a professional manner. That means the work paid for by the company doesn't stop when the code compiles successfully. If badgering doesn't work (and I doubt it will, but its a good step before you try more formal methods, and badgering doesn't have to be constant nagging - it can simply be a reminder when code is delivered that the dev has "accidentally forgotten" to include the docs too. I meant the same kind of badgering you get when you submit code for code review).

      In the end, the whole product needs to be developed: binaries, installation, support, maintenance, training - all these are part of what you need to do in a professional environment. Some will be done by others (eg. the user guide is sometimes written by technical authors depending on the size of the company - but even then, the dev will be explaining how it works to the tech author/BA/PM so the doc *can* be written), but some will be done by the dev and that's just part of the job.

      If you don't want to do that kind of job, you'll have to start your own company and work for yourself I guess.

  2. What?! Give them more money? by L4t3r4lu5 · · Score: 2, Funny

    But money costs money!

    --
    Finally had enough. Come see us over at https://soylentnews.org/
    1. Re:What?! Give them more money? by Moryath · · Score: 4, Insightful

      Your entire premise rests on a few bad assumptions, however:

      #1 - that the PHB will know what the fuck he is doing and adequately schedule enough time to document the code.
      #2 - that the marketing fucktards will know what the fuck THEY are doing and not overpromise or promise delivery schedules so tight that the PHB has time to allocate to documentation in the first place.
      #3 - that the company bosses are not "doing more with less" and overworking their employees to start with, relying on a down economy to fuck the working class by making everyone too scared to quit (for fear of not finding another job and being unable to support their families or being tied down by the risk of losing medical coverage) do 3-4 persons' jobs.

      Now let me tell you how the "real world", the world created by the Retardicans for the last 15 years works:
      - Employees ARE, as a general rule, overworked. The upper class HAVE, as a general rule, been playing the "do more with less" card so often that employees are doing the work that 5 years ago was done by 3 people.
      - Employees ARE, as a general rule, fucked by the system. Need to find another job? Better hope it covers healthcare. The upper class don't have to give a crap about health care, the poor will never get out of people poor because if they ever did medical bills will put them right back, and the middle class lives in daily fear of losing health care coverage and being put into the poorhouse by medical bills - for themselves, spouses, parents, kids, anyone in the family.
      - Managers are fucking assholes whose job it is not to work with the employees, not to ensure that enough time is allocated for things that need doing, but to be slave drivers. We just had a slashdot article covering the latest problem of people feeling too scared to take vacation because of how managers behave about it.

      What we need are far stronger worker protections. The Retardicans have been screaming about "obamacare obamacare obamacare" like it's some kind of bogeyman, but actually, single-payer and guaranteed healthcare coverage are GREAT for the working class, because it's removing the iron ball of "healthcare tied to your asshole fucking boss" from their legs and will let more people actually look for better jobs, or even start their own businesses without the fear of one accident or one unexpected illness ruining their entire lives.

    2. Re:What?! Give them more money? by Moryath · · Score: 2

      If you want worker protections, the first place you can start is by attaining a position of self employment.

      You try getting a "position of self employment" with a congenital condition.

      Want to take out a small business loan? Whoops - your "condition" carries a slightly higher risk, even if well managed, that you'll be incapacitated by it. So the bankers won't clear you for a loan.

      Want to try to buy health insurance for yourself or any employees? Fat fucking chance. No insurance will take you, "preexisting condition."

      Have a kid who's been born with something? Forget it, no coverage for them. Worse yet as happened to a buddy of mine who had gone the self-employed route - his kid has leukemia. Prognosis: 10 years max. 7 year old kid. Oh, to make matters worse, the health insurance company dropped his business, which leaves him, his wife, their kid, AND his 5 employees with no health insurance. To get it back, he'd have had to sign a "waiver" leaving his kid off of having insurance forevermore.

      Retardicans at work.

      but if I had lived on 1/2 of my income instead of 9/10 for the last 20 years

      You're assuming you HAD income that entire time. In the Retardican economy, chances are you've been laid off three times in the past 15 years through buyouts/acquisitions/mergers when some bigger company decided they wanted your current workplace's patents. You went through your savings each time, and maybe a little more, surviving till you were able to find another job. That's how the Retardican economic system works, unless you were born up at the top.

  3. I like to use a big stick by M4n · · Score: 2

    Nothing else seems to work...

    --
    In space no-one can hear your vuvuzela.
    1. Re:I like to use a big stick by robthebloke · · Score: 2

      Just move the offending developer to another poorly documented part of the codebase. Repeat that a few times, and they soon learn why code comments are a good idea....

    2. Re:I like to use a big stick by M4n · · Score: 2

      They seem to like it

      --
      In space no-one can hear your vuvuzela.
    3. Re:I like to use a big stick by Hognoxious · · Score: 2

      You're an Apple shop, right?

      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
    4. Re:I like to use a big stick by spooky_d · · Score: 3, Insightful

      Or they will show you why code comments are a bad idea.

      Code comments are usually unmaintainable artifacts; misleading at best.

      The best kind of documentation is architectural description of the solution. Everything else is just rubbish. I want to see code comments WHEN they are needed - and the fewer the better. If you write your code in such a manner that it needs documentation, then you might have done a bad job ad writing code.

      Example of moments when you NEED to document code: module boundaries, interfaces and implementation hints for when the code needs extension. But by no means should one document EVERY call; but the most important ones. Code samples would help.

      Just some programmer's opinion

  4. Mandate works best by Nickodeimus · · Score: 2, Insightful

    In this case, mandate works best because this is something that the developer SHOULD be doing anyways. Not documenting your code is inexcusable.

    1. Re:Mandate works best by netwarerip · · Score: 2

      But in a small to midsized shop, undocumented code is akin to job security (in developer's minds at least).
      If I had a nickel for every time I heard "Oh, be careful with what you say to (insert developer's name here), he is the only one that knows how the Widget process works." When I ask where the documentation is on it I get a blank stare, or worse, I get "Well, we asked him to do that but he says he's too busy."
      Ok, maybe that's more of a sign of lazy, ball-less management, but it still sucks.

    2. Re:Mandate works best by Anonymous Coward · · Score: 5, Funny

      /**
      * For the brave souls who get this far: You are the chosen ones,
      * the valiant knights of programming who toil away, without rest,
      * fixing our most awful code. To you, true saviors, kings of men,
      * I say this: never gonna give you up, never gonna let you down,
      * never gonna run around and desert you. Never gonna make you cry,
      * never gonna say goodbye. Never gonna tell a lie and hurt you.
      */

      //When I wrote this, only God and I understood what I was doing
      //Now, God only knows

      // I dedicate all this code, all my work, to my wife, Darlene, who will
      // have to support me and our three children and the dog once it gets
      // released into the public.

      // somedev1 - 6/7/02 Adding temporary tracking of Login screen
      // somedev2 - 5/22/07 Temporary my ass

      R.I.P - best question ever.

    3. Re:Mandate works best by Anonymous Coward · · Score: 5, Insightful

      Maybe it's a sign that the developer really is busy. Most places I've worked it's the developers who ask for additional project time to document code and aren't granted it because it's seen as a non profit generating part of the project (why have coders writing documentation for a finished project when they could be building the new project). It's shooting yourself in the foot for the future if you ever need to change anything in the code, but again, if that time is billable then efficiency savings from proper documentation are a very hard sell.

    4. Re:Mandate works best by LordLucless · · Score: 3, Informative

      No, it's perfectly excusable.

      Not giving your developers time to write documentation, by piling on another deadline as soon as the last bolus of code has been shoved out into production, yet still demanding that documentation somehow appear - that's inexcusable.

      --
      Just because you're paranoid doesn't mean there isn't an invisible demon about to eat your face
  5. code documents itself by lynnae · · Score: 3, Insightful

    I prefer the theory that well developed code is it's own documentation. (believe this comes from reading a lot from Uncle Bob)

    Crud loads of javadoc/msdn like documents aren't as effective as readable code and a few real world examples.

    1. Re:code documents itself by quintus_horatius · · Score: 5, Insightful

      In my experience, self-documenting code generally isn't.

      Proper documentation never explains what you're doing - that's what the code is for. Documentation explains why you did the things you did, which is difficult to express in self-documenting code.

    2. Re:code documents itself by sgtwilko · · Score: 3, Insightful

      I prefer the theory that well developed code is it's own documentation.

      I'm a Very strong believer in self documenting code, I simply don't allow my team to create objects, variables, functions, etc that don't tell you what they do.

      I'm also a strong believer in adding comments to code. Good, self documenting, code should tell you what it is doing without comments, but often the reason Why it needs to do things are is lost or cannot be conveyed in the code.

      tl;dr:
      Well written code tells you what it does.
      Well documented code tells you why it does what it does.

    3. Re:code documents itself by apcullen · · Score: 4, Interesting

      If by "self-documenting code" you mean code with milti-paragraph long comments in it explaining in detail what each section does and how it's intended to work, with a detailed change log at the top of each section of the code, then I agree with you.
      However IME to most developers "self-documenting code" means something more like "you should be smart enough to know how this works from reading my semi-descriptive variable names". I've seen comments like "Here's the main routine. This is fun" in some code that I've picked up and had to maintain. Made me shake my head at the time.
      When I first started my career, I met a developer who put a comment on almost every line of his code. When I asked him why, he said, "because I try to code like the next person who's going to look at what I did is an idiot. And it usually is. It's usually me". I laughed at the time, but as I've grown older I've come to realize how true it is.

    4. Re:code documents itself by Pokermike · · Score: 2

      Yes and no. Well written code tells fellow developers on the project how something works and shouldn't require a lot (if any documentation). However, if I'm using someone else's code I don't always want to have to read through it to figure out what it does. Documentation (like Javadoc) should be used to explain what the code does (without getting into the details of how). In some cases, a few real world examples may be enough.

      <rant>
      This is my problem with many open source projects. Usually the only way to use it in your own project is to open up their source code and start reading through it. And if there is any documentation, it's frequently woefully lacking and/or out of date. And tweaking their sample code doing "trial and error development" sucks.
      </rant>

    5. Re:code documents itself by Zerth · · Score: 3, Insightful

      Indeed, even if your code is complete clear on what it is doing, you should at least put in a comment on *why* it is doing what it is doing.

      Obviously, I used algorithm A, but why did I pick it over algorithm B. Is it because B isn't faster in this particular case or because A is less memory intensive, etc.

    6. Re:code documents itself by MobyDisk · · Score: 3, Informative

      If by "self-documenting code" you mean code with milti-paragraph long comments

      That is not what the term "self-documenting code" means. It actually means the opposite of that. The term refers to code with no comments, where the variable names, function names, etc. are so well-named that comments are less necessary. For example:


      float CalcPatients()
      { // Calculate an estimate of the number of patients based on
      // the number of beds per room,
      // the number of rooms, and the average occupancy rate. Since
      // this uses an average
      // occupancy rate, it is just a guess rather than an actual number.
      // So you might get fractional patients.

            return bpr * r * o;
      }

      float EstimateNumberOfPatients()
      {
            int beds = bedsPerRoom * rooms;
            int patients = beds * occupancyRate;
            return patients;
      }

      The latter is the self-documenting version.

    7. Re:code documents itself by radtea · · Score: 2

      I prefer the theory that well developed code is it's own documentation.

      I prefer the theory that developers who prefer the theory that well developed code is its own documentation are lazy and/or incompetent, so I don't hire them.

      --
      Blasphemy is a human right. Blasphemophobia kills.
    8. Re:code documents itself by radtea · · Score: 2

      The latter is the self-documenting version.

      The number of patients per what? Floor? Hospital? Wing?

      Neither version is well-documented, although the latter is better. All it needs is one line at the top saying, "Patients per based on average room occupancy rate" or something like that.

      One of the things that good comments do is provide context, and people who claim code is "self documenting" are generally junior developers who have never experienced how ad hoc code reuse and requirements drift can silently violate contextual assumptions in a way that introduces subtle bugs that aren't found until they bite you. Putting the context in the docs makes it easier to repurpose code properly and safely.

      --
      Blasphemy is a human right. Blasphemophobia kills.
  6. Indians will appreciate your docs by muon-catalyzed · · Score: 5, Funny

    Once the boss learns about financial advantages of outsourcing.

    1. Re:Indians will appreciate your docs by Robert+Zenz · · Score: 4, Funny

      Upcoming next article: "How to get Indian companies to document the code I payed for?"

    2. Re:Indians will appreciate your docs by dintech · · Score: 5, Funny

      And in our end-of-year special: "Why do my Indian offshore partners send back code that has Chinese comments in them?"

  7. Management issue by Anonymous Coward · · Score: 3, Insightful

    Management says "do X" as fast as you can. Programmer does X and report back. Documentation, like proper testing or elegant design, takes time and thus cost money. It often saves cost over the long term but if the management doesn't care why should the programmer ?

    1. Re:Management issue by Chrisq · · Score: 2

      Management says "do X" as fast as you can. Programmer does X and report back. Documentation, like proper testing or elegant design, takes time and thus cost money. It often saves cost over the long term but if the management doesn't care why should the programmer ?

      I've been there early on in my career. I had a tight deadline to produce something for the first iteration of testing. I said "its done but I need to document it. I was promptly told "we'll document it if we have any problems with it" and moved on to the next project.

  8. Documentation good, comments bad by WillerZ · · Score: 3, Insightful

    If what you need documenting is at the level of comments within a file your problem is not that your programmers aren't writing comments it's that they are not sriting good software. If meaningful class, method and variable names and sensible expression constructs are used there is no benefit to be had from comments.

    I'll make an exception for comments to explain why a given piece of code is not actually batshit insane but required to work with a third-party library you have to use.

    Producing documentation that spans classes and discusses how things are designed to work at run-time is, however, part of the job.

    --
    I guess today is a passable day to die.
    1. Re:Documentation good, comments bad by K.+S.+Kyosuke · · Score: 4, Insightful

      If what you need documenting is at the level of comments within a file your problem is not that your programmers aren't writing comments it's that they are not sriting good software. If meaningful class, method and variable names and sensible expression constructs are used there is no benefit to be had from comments.

      They should be all forced to pass HtDP with all exercises done properly and I bet a lot of them would actually start writing quality code (both quality as in "less bugs" and quality as in "readable"). I love the Amazon comment where a CS PhD admits that reading the book actually taught him to write code properly.

      (I have pretty much the same experience, having been subjected years ago to a typical "learn-the-syntax-of-Pascal-and-a-dozen-sorting-algorithms"-style first year of CS at my uni. But they never got around to teaching us how make your brain come up with code like the one in those nice textbook examples in the first place, what are the recurring code patterns (*not* design patterns, mind you). They have never ever once explained how to systematically go (for any problem in general) from a problem formulated in words to a working, readable code. Much like what Dijkstra about the contemporary math education - people memorizing proofs but having no idea how to "do math" in the first place, and teachers hand-waving every objection with saying that studens must "grow some intuition", but never explaining the processes involved explicitly. I believe I eventually got to the point where I started seeing the patterns, but explicitly formulated knowledge could have shortened the process by *years*. Go read the book, do the chores, see for yourself.)

      --
      Ezekiel 23:20
    2. Re:Documentation good, comments bad by djchristensen · · Score: 5, Insightful

      If meaningful class, method and variable names and sensible expression constructs are used there is no benefit to be had from comments.

      This is a naive viewpoint that gets repeated over and over, most likely from people who've never actually implemented or maintained anything more complicated than "hello, world". As a developer I strive to write the simplest possible code (but no simpler!) to solve a problem, but often that code is complex enough or is based on some non-obvious assumptions (device drivers, anyone?) that I can't even remember later exactly why something was done the way it was. Sure, if you write code for relatively simple problems that don't have to interact with other complicated pieces (like the OS or any libraries), you might get away with little or no documentation within the code, but that's not the world I live in.

      I do agree with others that external documentation is just as if not more important than internal comments. And while I'm very good with internal comments, I have to sheepishly admit I pretty much suck at doing the arguably more useful external documentation. Perhaps I haven't been adequately incentivised to do that, but then in most environments I've worked in, I get poked fun at for the level of comments I put in my code, not because they are excessive or unnecessary, but because most other code has almost no comments at all, so my code tends to stick out more than it should.

    3. Re:Documentation good, comments bad by __aaltlg1547 · · Score: 2

      Wrong. Comments should describe what programs are for, what assumptions it makes about parameters, classes, data structures, etc.

      If you have to read complex program code to figure out what it does, you are in trouble.

  9. Hire document experts by Maximum+Prophet · · Score: 4, Interesting

    I took a class at University many moons ago in software documentation. I got an 'A', and it was a valuable class in that I learned I sucked at it. (But I was better than most of the students)
    The teacher, with a PhD in English, was a master. She probably couldn't code worth much, but she could take unclear concepts and make them clear enough for a newbie.

    As long as you hire great programmers you are going to get great programs. If you want great documentation, you need a great documentor.

    --
    All ideas^H^H^H^H^Hprocesses in this post are Patent Pending. (as well as the process of patenting all postings)
    1. Re:Hire document experts by lkcl · · Score: 5, Interesting

      The teacher, with a PhD in English, was a master. She probably couldn't code worth much, but she could take unclear concepts and make them clear enough for a newbie.

      As long as you hire great programmers you are going to get great programs. If you want great documentation, you need a great documentor.

      it's funny you should mention this, because somewhere about 3 years ago wasn't there a slashdot article about some entrepreneur who didn't hire computer science majors (this was the U.S...) he hired english language majors and then trained them to program?

      the end-result was that he got people who produced better results because they were better able to express themselves and had already been trained to handle and comprehend more complex structures than people who thought they could program.

    2. Re:Hire document experts by ciderbrew · · Score: 2

      That reminds me. Must get a gymnast for a mistress.

  10. Don't Accept by Aladrin · · Score: 4, Informative

    Or simply don't accept code that isn't up to snuff. That includes documentation and testing. Peer review will help make this happen automatically. Here's how it goes:

    "I can't tell what this code is supposed to do."
    "It toggles the widget's status."
    "Is that documented somewhere?"
    "No."
    "Let's get that done."

    You don't have to have this happen too many times before you just do it to avoid that. Same as all the other good code practices.

    If you aren't doing peer review, you aren't getting the best code you could. It seems painful at first, but good developers actually like getting feedback on their code, and improving it. It isn't long before any good developer comes to desire it, instead of dread it.

    --
    "If you make people think they're thinking, they'll love you; But if you really make them think, they'll hate you." - DM
    1. Re:Don't Accept by dkleinsc · · Score: 4, Insightful

      You also need a culture that encourages documentation as well. I've met plenty of developers who are thoroughly convinced that the code is the only documentation that anyone would ever need. Here's the problem with that thinking:

      void frob_the_splutnik(int a, int b) {
                  s = get_splutnik()
                  s.frob(a, b)
      }

      That's definitely concise, and perfectly clear, but only if you already know what a splutnik is or why you'd want to frob it, and what a and b are supposed to signify. If you're a developer unfamiliar with this code base though, you have no clue what this means, not because you're dumb but because you've never encountered any of the concepts that the original coder had in mind.

      --
      I am officially gone from /. Long live http://www.soylentnews.com/
    2. Re:Don't Accept by Quince+alPillan · · Score: 2

      That's definitely concise, and perfectly clear...

      No it isn't. If you're in an industry where you're frobbing splutniks, you would expect developers to understand why splutniks need frobbing or else they should talk with someone to find out why they need frobbing. That way, through cross-training, you can understand the concept behind frobbing and are better able to utilize it in your code. In addition, a and b are horrible variable names and don't explain what they are and should provide insight into what is involved with the frobbing processes even if you don't know exactly what frobbing is.

      On the other hand, if you're in an industry where you're not commonly frobbing splutniks, you might explain why this splutnik needs frobbing or when you're being clever (such as inside the frobbing algorithm) or non-obvious to someone within the industry. A good rule of thumb might be if your project manager or supervisor can read the code and understand what it's doing.

    3. Re:Don't Accept by b4dc0d3r · · Score: 2

      People who think the code is the documentation would not, in my experience, do something so idiotic. If you work in a domain where everyone is expected to know those terms, it works. If not, you find better variable and function names.

      I always have clearly descriptive names, straight out of programming 101. That's mostly so I don't forget which one is which. The only 1-letter variables are counters, x, c, or i. And usually I use 'count', 'counter', 'index' or something else instead.

      The end result is, the code actually is self-documenting and needs no explanation other than bug fixes or algorithm changes for specific reasons.

  11. Recursive Logic by jrq · · Score: 2, Funny

    As I used to say "it was damn difficult to write, it should be bloody difficult to understand".

    --
    My UID is prime!
  12. Documentation not always worth it by DoofusOfDeath · · Score: 4, Interesting

    I'm growing increasingly convinced that in many situations, code only requires a minimal amount of documentation.

    Code under development changes rapidly, so most of that documentation would never get used. And lots of code is best explained by the code itself plus small, local comments, rather than by separate, copious documentation. And then there's the fact that software often gets discarded before anyone would need to make the kinds of modifications that required extensive documentation.

    It seems like sometimes, people who call for extensive documentation do so from the intuition that it's a diligent, long-term-smart strategy. I think the picture is muddier than that.

  13. Code Reviews and include in Job Description by realsilly · · Score: 2

    If you warn a developer up front that documentation of code is part of the job and you let them know there will be random code reviews they can't complain when they see no merit pay increases or eventually are laid off for now performing as expected. If a company does not allow for adequate time to have developers document code during a project it's the companies own fault, period.

    Developers have been told time and time again through-out the last 20-30 years that documenting your code is good coding practice, but a vast majority don't. There are several reasons, and the one I hate worst of all is the "job security" response. Be honest, you don't want to so you don't.

    --
    Life takes interesting turns, but the most interest is when you're off the beaten path.
  14. Surely I'm not the only one by AdrianKemp · · Score: 3, Interesting

    I've never had a problem of incentive or motivation to document my code; my problem is and always has been time.

    Documenting anything other than conceptual stuff from the beginning is a bit of a waste (though far from a complete one) because the final product (due to bug fixes/spec changes/etc) never matches what you set out to do.

    So when you do get to the point of post-testing where the code has stabilized and it's time to really sit down and document everything fully you're being given new stuff to work on. Sure I can (and do) raise a bit of a fuss about it and explain that if it doesn't get documented *now* it'll never get documented *well*. That always seems to fall on deaf ears though.

    I think a lot of it is that the deserved biting in the ass never comes. Shortened product life cycles and customers that have become (wrongly) more tolerant of buggy software in production environments means that you can stumble through with a vague knowledge of the product and never really get fucked. It's the same basic reason that so many bad programmers have jobs.

    1. Re:Surely I'm not the only one by Assmasher · · Score: 2

      This is why you "document your code" as you write it.

      There's no reason you can't document your code as it is being written, in fact, it's the best time to do it because the documenting the *reason* you choose to do something a particular way can actually be more important than ensuring that the following code is easy to follow.

      There are, of course, limits to what you should document in code. For example, I wrote a software renderer in Java two years ago and there is a section that relies on some hidden surface removal techniques covered well in Abrash's book(s) but very complicated to explain in the level of detail that any software engineer would understand because explaining it relied on a corpus of knowledge not common to software engineers. My documentation in the code explained it rudimentarily and then pointed anyone else reading it to some references for greater understanding. That was the one place in the code I did that, and it was the first time I've done that in code comments before.

      BTW, it is quite often more valuable to give your variables and arguments clear names that intimate their usage and intent than over the top code commenting - but it all helps.

      float[][] m_aHiddenSurfaceRemovalScanlineFragments_Z;

      is much more clear than

      float[][] m_aHSRFragsZ;

      (Ignoring our Hungarian notation approach of course)

      BTW, names like that can be a lot of typing, so we usually write, build, test, validate, refactor for clarity, then check-in.

      --
      Loading...
  15. Anatomy of a documented method by Ouija · · Score: 4, Insightful

    // WHY
    int WHAT(...) {
          return HOW();
    }

    --

    -Ouija- poke 53280,11:poke 53281,12
  16. too much formulaic crap by dltaylor · · Score: 2

    I write comments when what I'm doing is "clever", or hardware-required. Otherwise, I use meaningful labels and a readable syntax (C, for example, is K&R, except that all block-opening braces are on the next line for easy "line-up", any code beyond the current line has braces; variables have meaningful, not formulaic, names).

    Too many managers and "religious" programmers want forty lines of comments for a twelve-line function. They ain't getting it from me, and, so far, my peers are happy with what I do. I comment shell scripts, PHP, Perl (more than the others), ... when there's a real reason, not just to fill out some silly "comments requirement". I put useful comments in svn checkins, too. Those are probably more meaningful than most of the code comments I have seen.

  17. design document vs. documenting source code? by us7892 · · Score: 3, Interesting

    I've found two camps at my company. Both camps document their code with comments and meaningful commentary. It is more a matter of the "design document" that describes the product or project that is a problem. The document that is perhaps supposed to guide the overall architecture of the product, and thus, the architecture of the classes, methods, interfaces, etc., aka. "the code".

    The first camp of developers just wants to get in and start coding. They often say "I need to code to figure it out." The actual web site works well, but new developers have a tough time maintaining that same site. The original developers are pretty much the only ones that can change the critical aspects of the site, and even then, as time goes by, that becomes difficult. But, they got the site up and live in the time allotted. And they wrote a 2 page "design document" when they were done - the doc was useless.

    The second camp of developers writes a 50 page design, then starts coding. The actual web site works well, but the overall time to get the site up and live took 5 times longer (that includes the time to document.) The documentation evolved with the changes that were made along the way. Maintaining this same site went well at first, since the documentation was great. But, the docs slowly get neglected, and in a couple years, this site is difficult to maintain.

    In the end, perhaps there is a happy medium. A "good enough" design document, and get started coding relatively soon. I used to lean toward the second camp, but now I lean toward the first camp :)

  18. It's A Question of Honor by Gallenod · · Score: 2

    "What!?! Comment my code? You question my honor! I'll kill you where you stand!"
    -- Mukluk, Klingon Programmer

    --

    TLR

    A man no more knows his destiny than a tea leaf knows the history of the East India Company
  19. Catch 22 by Kjella · · Score: 2

    Documentation doesn't really have all that much value unless you can trust it, and in a large organization with a large code base there's likely to be code where the documentation is incomplete, inaccurate or plain old outdated and wrong. Once you cease trusting the comments and realize you must read the code to actually be sure what it does it turns into an evil circle. Nobody bothers to look at the documentation because it's useless and because it's useless nobody bothers to fix the documentation. And you fixing a few snippets here and there isn't going to change that perception and break that circle.

    Like with structured code it's a lot easier to trash a code base than it is to keep it clean. You can apply a quick fix to the code and it works, but as you get layers or layers of hacks and quick fixes it grinds to a halt. For a time nobody's going to realize the documentation is deteriorating either, it's only as people lose more and more grip on what's going on - usually after key people left - that you're now spending more and more time locating the problem. And since there's no clear system to things, you keep adding more hacks.

    Lack of documentation is just another form of technical debt, and like the entire economy we like to push that debt ahead of us. Maybe next week you'll get another job or get downsized or get outsourced or management will decide to replace it with a different tool or you'll be promoted or reorganized so it's no longer your problem. Meeting deadlines or performance goals now is more important than maintenance later. And your manager, well he's probably got no longer perspective than you, make the executives happy, collect a good paycheck, get a good reference.

    Actually it seems a miracle that we produce software that keeps working, because it doesn't seem like much of anyone is in it for the long term. Workers care about their performance and keeping their jobs this quarter, CEOs and stock holders care about the stock price this quarter and that goes for most people in between. Documentation is cost and nobody wants to take the cost in this quarter if they can take it in next quarter. I've seen companies work extremely hard to get income booked in the current quarter or FY, not because of the two days but because of bonuses and such.

    --
    Live today, because you never know what tomorrow brings
  20. Simple solution by msobkow · · Score: 2

    Make time in the schedule to do the documentation.

    When you're already working a 50-60 hour week just to get something out the door because some moron cut your estimate in half before promising a delivery date, where are you supposed to find the TIME to document instead of code, test, and ship?

    Programmers may hate doing documentation, but it's MANAGEMENT's fault it doesn't get done. Period.

    --
    I do not fail; I succeed at finding out what does not work.
  21. I disagree by acomj · · Score: 4, Insightful

    As someone who's started a new position and using classes with No comments, I can say I've wasted a good deal of time trying to figure out what certain public methods and certain classes do. They've used good naming conventions, but even so there is some subtly about what is done that could have used some explaining, plus looking through 1000s of lines of code before using a method isn't time effective. Its would be far easier for me to read through method header with inputs/outputs than to slog through code trying to figure out if this is the method I want. I don't want every line commented (I've seen that some placws), just the jist .

    I came from an internal api writing group, and those using our code would just ask us questions if they couldn't figure stuff out, and we rsther they didn't so we documented ..

    Examples or some test code I agree are super useful.

  22. Re:Fire them if they don't by BVis · · Score: 3, Insightful

    I hope to $deity you're not a manager. Your morale must be terrible if you do.

    I have to echo other commenters: If you want well documented code, you need to allow sufficient time for said documentation to be written. Failure to do so isn't a failure in programming, it's a failure by management to build realistic timelines based on feedback from programmers.

    If your programmers are constantly telling you they need more time, on project after project after project, and it's ALL of them, not just a few complainers, then you need to look in the mirror to find the source of the problem. Go to sales/marketing, read them the riot act about promising impossible deadlines, and get THEM fired if they continue to promise unicorns on a wombat budget.

    --
    Never underestimate the power of stupid people in large groups.
  23. Don't document your code ! by eulernet · · Score: 2

    As an agile developer, I recommend against documenting your code.

    You need to document the algorithms, but never the code.

    Documenting your code will require you a lot of maintenance. Every time you change your code, you need to change your documentation. It's a never-ending process.

    Instead, decide on a meaningful notation for your routines names (so any coder knows what the routine is supposed to do), and write tests, or more exactly functional tests.
    Tests have a few goals:
    1) check that your code behaves as expected.
    Suppose that you have to fix a bug in your code, without tests, you cannot be sure that the fix will not be harmful.
    It also allows greater flexibility in your code, and it will not smell like a rotting corpse.
    2) show how to call your code, in order to get results. Examples are very useful for other developers.
    3) confirm a behaviour. Your code does something, but sometimes, it's not clear. Your test should demonstrate the value of your code.
    4) improve the stability of your program, and reduce the QA time.

    Once the habit of writing tests is acquired, you'll start writing the tests before the code.
    This is called TDD (Test Driven Development), and helps reduce a lot the amount of code you need to write, because you only write useful code.
    Who wants to write unused tested code ?

  24. make them troubleshoot it by misfit815 · · Score: 3, Interesting

    I work for a firm that conducts a periodic release of code to its production environment. Those of us who regularly work the "release night" know what it means to document code well (and no, it's not just comments in the code). What our firm, and others like us, needs to do is rotate everyone through that situation, or others like it, so that they can see the flipside of their effort. Having to troubleshoot poorly documented code is a good way to instill in a developer good documentation habits.

    --
    Jesus told him, "I am the way, the truth, and the life. No one can come to the Father except through me. - John 14:6 NLT
  25. Programmers != Software engineers by ktrnka · · Score: 2

    If you want documentation and comments, to start with you should stop calling them programmers.

    If you want documentation and comments, you call them software engineers and you allocate time for documentation, commenting, optimization, debugging, and other critical non-functionality tasks. Managers typically only allocate time to develop something that sort of works, not something that's polished, maintainable, debuggable, extensible.

  26. It's a matter of time and nothing else by chimerafun · · Score: 2

    I've run several engineering departments. Some have been good at documentation, others not so good. What's the difference? It's quite simple. Time When a company demands quick turnaround, its all the developer can do to get the code out the door. Good documentation falls by the wayside in these instances. In my experience its more about demands from the top than anything else.

  27. Automatically enforce it by Routrout · · Score: 2

    The best way to have programmers write quality code is to automatically enforce it. Have an automated tool verify the code for comments and run it on your build server each time new code is committed. I am a .NET developper, so each time I commit code, StyleCop and FxCop are run on the build server. This means my code is always commented, hell even spelling errors are not allowed! If I am too lazy to comment, the build server sends an email to the whole team informing them of my laziness.

  28. I document for myself by tuffy · · Score: 3, Insightful

    Six months from now, long after I've moved on to something completely different, am I going to remember a function's return values? The inner workings of a particularly complex algorithm? Or the reasoning while a special case has to be handled differently?

    If it's not going to be obvious to myself later on, it's worth adding a concise comment to explain.

    --

    Ita erat quando hic adveni.

  29. What is the goal by EmperorOfCanada · · Score: 2

    First, what is the goal? The goal is not well documented code, what use to anyone is well documented code by itself. What you are looking for is a product that works and is easily maintained. Good code and any documentation is a huge part of easy to maintain. But where many people go wrong is that they see code documentation and commenting a critical part of a project. To the point where it starts to interfere with the creation of a good product that is easy to maintain.

    So when looking at documentation it needs to make sense for the endgame. Who is going to use it? When are they going to use it? How much effort is going into its creation? I have seen projects where thousands of pages of documentation were generated where the only thing ever read again(other than by the document review team) were the few pages that documented the steps for configuring the server. When the next version was created nobody referred once to the old pile of documents that had every detail in the universe.

    The next question is: what is documentation? This might seem odd but documentation can be the very directory structure itself. I wonder where the client code, maybe it is in the directory named client_code.

    In agile or XP programing you don't tend to look too far into the future. So two critical documents that would be very active are your todo list for this cycle and a wishlist for future cycles that eventually turns into a todo list. The todo list, when done, can be chopped up into a crude set of documents that show the past if anyone were to be interested.

    Lastly the code itself is an excellent place for documentation. A quick explanation of what it is about and why it exists can be useful if the file isn't already named verifycreditcardnumber.c.

    So I don't think the criteria is so much poor or good documentation; so much as it is about useful documentation. If non programmers are intimately involved then lots of screen shots, text, and flowcharts are needed. If programmers are the only parties then it might almost all hide in the codebase with the exception of the screenshots mockups.

  30. I never understood this... by roc97007 · · Score: 3, Insightful

    I always document my code. It saves time later. Six months down the road I'm not asking myself "why the hell did I do that?" It's for my own protection. I've had programmers tell me that they don't document their code because it's obvious what the code does, and sometimes that's true. But I think at least some of the resistance later to add features or fix bugs has to do with not wanting to struggle to remember what the code does. And -- this is just me, but -- you probably don't want to have a reputation for being uncooperative and not a team player in a down economy.

    In a very early job, a guy with more credentials than I wrote a program we all used in a language I didn't know. There was a longstanding bug which he refused to fix [1], and he kept the source in a protected directory. So one night we broke into his account, I scooped the completely undocumented code, figured out the problem (had to change *one* (1) character!) and distributed the new binary. It took him awhile to figure out what happened. Boy was he pissed.

    [1] Whether this was a dominance game or he really did not want to try to figure out the code he had written months earlier was a point lost in history.

    --
    Oliver's law of assumed responsibility: If you're seen fixing it, you will be blamed for breaking it.
    1. Re:I never understood this... by roc97007 · · Score: 3, Interesting

      > I have also seen companies with a turnover history due to replacing experienced workers with cheaper labor and this kind of culture will frighten engineers into a protective mode, and they won't comment their code for fear of getting replaced.

      I'm living that dream right now; we've replaced a couple hundred experienced, in some cases brilliant IT people with convenience store shelf replenishers with only a few weeks training. So it does happen. And yes, it has been an unmitigated disaster.

      The problem is, the people who make the decision are not the people equipped to understand the ramifications of uncommented code. Even when it's pointed out to them that they're going to lose a gigantic amount of crucial tribal knowledge, they'll go ahead, with dollar signs dancing in their eyes, and pull the ripcord anyway. And then what comes out of the bag is a bunch of camping gear instead of a parachute. (Sorry, I just flashed back to an old Road Runner cartoon.)

      The point is, not documenting your code is not a good strategy for job retention, for the reason you state (when this behavior is spotted they're more likely to be replaced with someone who's better at documentation) and also for the reason that upper management isn't even aware that code has comments, or that it's not a "procedure", it's the culmination of a lot of knowledge and experience, which isn't easily replaced by a written set of instructions. I would also add that a crew who is secretive, doesn't work well together, and takes forever to fix stuff due to having to reverse-engineer their code, is more likely to be outsourced than people who are doing their jobs properly. I hasten to add, crap happens even to good teams (it did here) but it makes it easier to argue against the decision if you're defending a stellar team.

      --
      Oliver's law of assumed responsibility: If you're seen fixing it, you will be blamed for breaking it.
  31. Real World by geoffrobinson · · Score: 2

    I will document when I'm given the time to document.

    If it's always the tyranny of the urgent, if there's always some fire to put out, I won't have the time to document.

    I had a job where the manager was always complaining we didn't document. But he never fought upper management to give us time to document.

    If you say "I have to have documentation and it is a deliverable" you will get it. If there is always something more important to do, it won't get done.

    --
    Except for ending slavery, the Nazis, communism, & securing American independence, war has never solved anything.
  32. The Code Isn't the Problem by Greyfox · · Score: 2
    Code doesn't happen in a void. It's there to support the business. If you understand your company's products, business logic and the customers they sell to, you can write good code to support those processes. It is the business which you must explain to new arrivals on the team. It is the business logic which must be clear to anyone supporting the code.

    The agile people say you must never comment at all because you might change the code and then your comments will be wrong. This is only true if you're describing what the code is doing. If you are describing how the code supports the business, the comments will probably still be correct.

    The scholarly types say you must comment profusely. Certainly comments help in areas where the code might be confusing for a newcomer, but no amount of describing what the code is doing in any given piece of code will shed much insight onto the business processes that code supports. Many programmers out there are just... bad... and they will probably not read the comments and screw up your code, anyway. Not that this is a reason not to comment your code. Having a comment with a warning might constitute useful proof of a given programmer's... badness... in the event that your code is screwed up in the future. If you comment, it is wise to make sure the evidence is something you wouldn't mind having come to light in the future.

    Code itself is a specialized language by which two programmers can communicate, often across a gap of many years. An understanding of the business is both required and usually assumed by one programmer or another. If one of the two programmers has a less-than-perfect understanding of the business, his code will reflect his confusion. If the programmer reading the code has a less-than-perfect understanding of the business, he will find the code confusing no matter how good the comments are. If both programmers have a less-than-perfect understanding of the business... well... that's the situation we most often find ourselves in. And that's usually when people start complaining about documentation.

    --

    I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

  33. You make it a thing everyone does by Sycraft-fu · · Score: 2

    It really can be done. If your company has a culture where it is just how things are done, people will do it because it'll be more bother for them not to (as they'll get bothered when they don't).

    I'm not saying it is trivial to do, just that it can be done. You have a corporate culture where that is how it is done, and people on all levels understand it, it'll be done. When the John Wayne programmer who refuses to do it comes in, he'll learn when every time he submits code it gets kicked back and the team lead comes and explains again that you have to follow certain conventions, document, and so on.

    As an example of where it does happen would be Microsoft. If you talk to anyone who's seen the Windows source (either at one of the many universities that has a license to have it, or from the leak a few years back) they'll tell you it is very good in that regard. It follows consistent conventions, is well documented, and so on. That isn't coincidence, it is because they have a culture that demands that.

    I expect it is also the sort of thing you seem more of the bigger and longer term the item is you are talking about. Something like an entire OS like Windows (where you are talking a ton of functionality, not just a kernel) is going to require a good setup since the code will be around for a long time and worked on by many people, and is exceedingly large and complex. When you are talking little "fix it" programs as many people have to do to make something work as a sysadmin, then it is less likely to happen.

  34. Document the "Why" not the "what" by 140Mandak262Jamuna · · Score: 2
    Ridiculous, useless, redundant comments reduce the signal to noise ratio. I would term "This function calculates the area of a triangle" or "this function changes the state of widget" to this category. Just pick some very sensible function/class names and be done with it.

    What must be documented are the complex procedures and why it is doing it. Or if a previous simpler approach has been tried and then removed for a different non obvious procedure, that fact must be documented. Example:

    "This class maintains a multi map of triangle pointers, sorted by area, to solid body faces. The sort key is a double, the truncation errors differ between Linux and Windows, so the order of visitation is not the same. When we used a simple std::multimap(Triangle *, FaceList, double),[*], the tables had different orders in different platforms. To provide repeatability we use a tolerance and tie breakers to make sure in both platforms the table will have the same order. It is called by render class, in a not very deeply nested loop. So CPU performance is NOT critical. Code is written for ease of maintenance and development, not optimized for CPU or memory." Such comments are useful, if maintained and kept up to date.

    But most of the time it is not done. You see beautifully formatted comments created by macros in the editor, that occupies so much of screen real estate, I am not able to see both the code and the comment. Example:

    [*] Syntax nazis: Slashdot formatter would not let me use angle brackets there. So I used () for illustration. /***Function Foo**/

    /**Author Iman I Diot**/

    /**Date 1993 Aug 21**/

    /**Returns bool**/

    /**Input int**/

    it so stupid, I feel like screaming. If that coder is still working for me, I can scream at him or her. But mostly it is people who have left the company ages ago dumping that legacy POS on my lap.

    --
    sed -e 's/Chuck Norris/Rajnikant/g' joke > fact
  35. Documenting the "whys" of code by Windwraith · · Score: 2

    I often hear that the proper approach is to document WHY you did something.
    I am not a coding guru or even have formal studies on that field, I am really just a hobbyist, so anyone here has a few good valid examples of a "why"? I'd like to comment stuff properly.
    So far I use non-shortened descriptive names for variables, functions and types, but I don't use that many comments. For example when parsing tokens in a string I write stuff like "//The format is ", but even so I feel the code is doing a better job at explaining it than I do.
    As I went with the lengthy names, I have less problems getting lost on my own code, but I feel I am misbehaving. I blame my lack of formal education in coding, but would like to have some quality standards nevertheless.

    1. Re:Documenting the "whys" of code by Windwraith · · Score: 2

      Well, the way I name functions, it's usually "ship_calculate_arrival_time" (in a "component,action" fashion, so they sort alphabetically as well), but point taken.

  36. Measuring readability by John+Bayko · · Score: 3, Informative

    I think the real problem is trying to measure code readability. Policies and coding standards try to address the issue while avoiding it by mandating frills that they think will kind or "imply" readability - function length, number of spaces in parentheses, badly defined Hungarian notation (dead, thankfully), Javadoc or similar commenting standards, and so on. But there's no getting around the fact that the only way to measure code readability is to read it.

    This means that you need to put code review at the centre of the process. Not necessarily anything heavyweight, but just require that one other developer reads and understands the code (and points out any obvious flaws) before committing - with the limit that any questions the reviewer has should only be answered by changes in the code, because a question implies a readability problem. The developer can add comments, or rename variables, or restructure the code to make it clearer, but the end result should be readable code with fewer bugs (bugs live in hard-to-understand code, simply adding some intermediate variables to a complex formula can make them go away).

    As long as the code review itself doesn't get bogged down with issues of How The World Should Indent and things like that - that's always a risk with developers looking at each others code.

    1. Re:Measuring readability by rufty_tufty · · Score: 2

      As long as the code review itself doesn't get bogged down with issues of How The World Should Indent and things like that - that's always a risk with developers looking at each others code.

      That's why my favourite style to do code reviews was "Justify your warnings" from the various tools that read the code.
      Most people agree that some warnings are just the compiler being over-zealous, and those parts of the review went fast; but those around bits of code that others didn't understand took a lot longer (this also encouraged you to get rid of the easy warnings and sloppy code before review just out of laziness), those warnings that scared people but you were sure was just because you had no other choice again gave valuable feedback.
      It worked well for us anyway...

      --
      "The weirdest thing about a mind, is that every answer that you find, is the basis of a brand new cliche" -
  37. Good Enough by tomhath · · Score: 2
    FTA:

    useful rule of thumb is that programmers should produce documentation that's "good enough" -- and no more. If it gets the job done, it's probably good enough. Any additions are just as likely to be redundant. If that sounds vague, that's because it is;

    Thanks Mr. McAllister, that clears it up completely. Bribe, threaten, or otherwise coerce programmers to do ... something, but I don't know what that something is.

    I worked on a very large project a few years ago where the company did a study to correlate the number of comments with the number of reported bugs in the code. It revealed exactly what I already knew: the more comments in the code, the more bugs were reported against it. There are several reasons for that (complexity of code, skill of programmer, etc). Fact was that while fixing all those bugs we found that the comments around the bad code were usually incorrect: the code didn't do what the documentation said it did. So out of necessity we adapted to the situation, first thing to do when fixing broken code was remove the comments (because you shouldn't trust them), then figure out what the code really did, fix it to do what it was supposed to do, and (possibly) add back a few succinct comments that were correct.