Become a fan of Slashdot on Facebook

 



Forgot your password?
typodupeerror
×
Businesses Programming IT Technology

The Importance of Commenting and Documenting Code? 203

mrtrumbe asks: "The company I work for is in the process of creating a development standard to be applied to all projects. The topics being considered range from dictating the formatting of the code (an issue on which there is widespread agreement), to creating a standard for commenting and documenting the code (a far more contentious issue). On the issue of commenting and documenting, there are two extreme views being considered with most employees' opinions falling somewhere between them." To comment, or not to comment. And if you do choose to comment, what's the best way to standardize it, company-wide?
"The first view is that commenting and documentation will protect the firm from bad programmers or a programmer abruptly leaving, make the code far easier to understand to someone unfamiliar with the codebase, and are necessary for all public, private and test code. The opposing view is that there are more effective ways to mitigate the risk of bad and disappearing programmers (like mandated shared ownership of code and sufficient oversight), that comments are not necessary for clarity and can be dangerous if not kept up to date (which is considered likely), and that documentation is necessary only for public code. Where does Slashdot stand on this issue? Please share any success stories and recommendations for a company-wide standard on commenting and documentation of code.
This discussion has been archived. No new comments can be posted.

The Importance of Commenting and Documenting Code?

Comments Filter:
  • by yagu ( 721525 ) * <yayagu@[ ]il.com ['gma' in gap]> on Monday January 09, 2006 @12:40PM (#14428125) Journal

    Stop it! Stop it! Stop it! The Noise. Make it stop!

    No, seriously, you cannot comment your code and enforce that as policy. You can't impose standards and impose enforce that! It doesn't work.

    You either know how to program/code, and commenting is part of that, or you don't. Either your staff knows same or doesn't.

    Go ahead and establish "guidelines", you'll feel better. But I've been in this industry for over 20 years and applying "standards" for coding and "comments" has never worked.

    Write un-obfuscated code, have peer reviews and walkthroughs, and have staff that know how to create... It's really all you need.

    (As an anecdotal experience -- we had "standards" on a major project, and I accidentally created a Class without the proper capitalization. A peer came to me and confronted me on said transgression and wondered what I intended to do about it. I said I intended to let it slide and would try to be better in the future. He insisted we "fix" this problem and we spent (and I'm NOT making this up!) the next day's worth of time re-factoring the code (the IDE wasn't up to speed for this -- thanks Microsoft) to "correct" the "problem". Sigh)

  • by V. Mole ( 9567 ) on Monday January 09, 2006 @12:52PM (#14428230) Homepage

    Comments won't protect you against bad programmers; they'll write bad/confusing code and comments no matter what.

    However, I've found that writing semi-structured comments for each module and function (or object/method, if that's your poison) using something like doxygen is worthwhile for ongoing maintenance. It helps others see what the intent is, and provides a basis for writing unit tests. It even helps the original coder when they come back to the module 6 months later. It's not a matter of whether it's public code, just basic internal docs.

  • by ArwynH ( 883499 ) on Monday January 09, 2006 @12:59PM (#14428311)

    Commenting and documenting code is something all programmers should do. Not doing it is highly unprofessional and should not be allowed in any self-respecting firm. Making sure the documentation/comments are upto date is included in that statement.

    On the other hand just because code is well documented that doesn't mean it's easily maintainable. There are various techniques used to generate good maintainable code. But without documentation any code more complex that 'hello world' tends to be a pain to maintain no matter what techniques you use.

    I personaly also find the formating of code (and comments) just as important as commenting it. Reading code formated in a way you're not used to can be a pain and reading code formated in different ways doubly so. So a company-wide standard for formating code/comments would be a good idea.

  • by MarkusQ ( 450076 ) on Monday January 09, 2006 @01:03PM (#14428357) Journal

    There is one problem with comments, but it is a show stopper as far as I'm concerned.

    Computers never read the comments, while programmers tend to read comments rather than code. The first part is obvious, and the second is easy to demonstrate. Together, they are a recipe for disaster.

    Uncommented code has a number of disadvantages, but the overriding (IMHO) advantage is that both the computer and the programmer are dealing with the same thing, the code. On the other hand, with commented code they are dealing with two similar but distinct things, that are related in exactly the same way as a fine-print contract (the code) and the car salesman's verbal promises (the comments). When push comes to shove, the salesman's words mean nothing and the contract is what matters. So why even listen to the salesman?

    -- MarkusQ

    P.S. This is not to say that I never comment code; only that I do so sparingly and never trust the comments.

  • Re:Documentation (Score:5, Insightful)

    by anomalous cohort ( 704239 ) on Monday January 09, 2006 @01:10PM (#14428436) Homepage Journal

    In addition, consider the following points.

    • Code comments are only one form of developer documentation. Other forms include design and discovery docs (e.g. UML) and change comments (e.g. this change fixes bug 2938). Put design/discovery docs in an Intranet collaboration site. Wiki or any CMS such as Plone are good technologies for this. Put change comments in your source code control system.
    • Code comments should answer why, not what. As stated elsewhere, commenting is not a replacement for compentency. Any compentent developer can read most business application style programming and figure out what is going on. What you cannot read from the code was that meeting where some influential user or other relevant stakeholder insisted on a certain approach or placed high value on a certain outcome.
    • Code comments should not insult the intelligence of your average programmer. If you are coding a simulated annealing or genetic programming algorithm, then providing a URL to the appropriate material in the code is sufficient. If you are looping through some recordset for search or data aggregation purposes (which is about 90% of your business application coding), then you don't really need to provide a comment to the affect that that is what you are doing.
  • In the real world, you work on a project for a time then move on to something else. Then you or someone else is assigned to revisit your old code. You don't have time to relearn the code and you certainly don't have time to sit down the guy called in to fix it and tranfers your understanding of the project. (If you did, you would've documented the code properly in the first place, right?)

    When companies don't comment and don't document their code properly, they begin this vicious cycle of rewriting old code because no one know how it should or does work and no one has the time to figure it out. Let me explain why.

    Imagine you find a software package on the internet licensed in a way that suits your needs. Now imagine that software package, with very few modifications, will do exactly what you need it to do for you project. You have a choice: (1) Take that software, modify it, and deploy it, or (2) write your own from scratch.

    There is only ONE determining factor in whether you inevitably choose (1) or (2), and that is DOCUMENTATION.

    Now remember that software you find in your own company is no better or worse than software you find on the internet, only it has a much more liberal license for your purposes. But does that change the fact that in order to make use of it you have to understand it?

    On my job, I have an approach to undocumented software. I start writing documentation for it, whether or not the author wants me to and whether or not there is really enough time for it. If I have questions, I find the author, and approach him with pen and paper. We sit down and write documentation together. Inevitably, by documenting what I find in other people's codes it ends up saving me more time than if I wrote the code myself, documented it, and debugged it. So I have been able to finish a great number of projects ahead of schedule because I don't write code: I READ it. (And this is a perl world too!) And in the end, others are able to come and read my documents and notes and reuse the software as well.
  • by Rakshasa Taisab ( 244699 ) on Monday January 09, 2006 @01:20PM (#14428545) Homepage
    Ops, you just lost all the developers who manage to write code that is so clear it doesn't need comments.
  • Theory vs Practice (Score:3, Insightful)

    by SmallFurryCreature ( 593017 ) on Monday January 09, 2006 @01:26PM (#14428603) Journal
    Commenting and Documenting both take time. Wich you often don't have, so you don't do it or worse do it badly.

    If somebody asks you to code something (and you can get away with it) tell them this, "okay that is X hours for just the code and X*3 for the code and proper documentation."

    Yes I made the *3 up. You know why? Because I have always had the misfortune on working on the kinds of projects where I either didn't get the time needed or the guy before me didn't do the documentation.

    If you want to take a ride in your car you should walk around it making sure it is in proper working order like all the lights working. It is a law and enforced by people with guns. Now how many of you do it?

    Okay, nobody. So now you are under time pressure, you are underpayed and overworked and you got a choice, either deliver on time or tell your boss your still writing documentation on the installer.

    When I was still young and fresh I thought that following procedures is the way to do it. Boy was I wrong. The secret? Code fast and ugly and make sure you have moved on before the shit hits the fan. Oh and never ever be lumbered with a maintenance project. I never even seen documentation wich was up-to-date.

    The entire discussion on wether or not to document is wrong. The discussion should be wether you will allot enough time to non-coding work. It applies to so many things, peer review of code, sharing and re-use of selfmade libraries, layout standards, knowledge sharing, etc etc.

    The larger the company the more time can successfully be spend on non-coding things that however are always badly reviewed during your evalutation. Oh yeah very nice you tought everyone else how to code securely and made sure nobody else has bugs in their code. Now how many lines did you write? Oh, no pay rise for you.

    So simply ask this of the people in favor of proper documentation. How will they find the time?

    And ask the non documentation people if they will do the maintenance on their own projects 10 years in to the future.

    My experience? I needly predict I need X to write code and then Y to write the proper documentation. I deliver the code and get the next project and if I protest that I am still working on the documentation then I am told that it can wait. I am still waiting. Oh and the risk of doing it properly? You get lumbered with writing maintenance and writing the documentation for everyone else because your good at it but a slow coder. ARGH!

    Just comment the basics, point out in a readme.txt where to start reading and tell them wich bar in the neighbourhood serves hard liquor during lunch. Oh and if you comment some code out come back later and delete it. Can be very confusing if you have to wade through a problem where 2/3's is old code.

  • by NathanBFH ( 558218 ) on Monday January 09, 2006 @01:32PM (#14428647)
    For significantly complicated projects, those programmers don't exist. If you think commenting your code is an unreasonable job requirement, I will fire you.
  • by ogar572 ( 531320 ) on Monday January 09, 2006 @01:36PM (#14428685)
    is have all the programmers program in the same style and guidelines. Examples include all SQL statements start with $sql_, making sure code is properly indented, variable naming that are easy to recognize, where certain functions should be placed in the directory structure, and the such. Simple things like that should eliminate the need to write a novel for every piece of software that you write.
  • simple rule (Score:2, Insightful)

    by outcast36 ( 696132 ) on Monday January 09, 2006 @01:49PM (#14428824) Homepage
    Document at the function level (javadoc style is nice). It's easy to remember and it helps you refactor. If you are documenting the internal magic, then the magic could probably be moved out into it's own function, which then gets it's own documentation. voila.

    If you need a documentation/commenting consultant, I am available to guide your team through this process.
  • by gnovos ( 447128 ) <gnovos@ c h i p p e d . net> on Monday January 09, 2006 @02:08PM (#14428994) Homepage Journal
    For significantly complicated projects, those programmers don't exist. If you think commenting your code is an unreasonable job requirement, I will fire you.

    I have yet to see a project, in 11 years of coding, that is so complex that comments are a REQUIREMENT. If you don't know how to refactor, and how to reduce your bloated thousand-line long methods into a series of simple to understand 10-line long methods, you still have much to learn about good code.
  • by Randolpho ( 628485 ) on Monday January 09, 2006 @02:33PM (#14429257) Homepage Journal
    Even if you're the best normalizer/refactorer (is "refactorer" a word?) in the world, you had better explain what a function or method or class or aspect or (etc..) does, how it's used, and what the expected results are, or you have made code that is a nightmare to maintain.

    In truth, function-point comments of a well-normalized/refactored program represent easily 99% of the necessary commentation for a program. The only time you ever really need comments otherwise is to explain a particularly tricky algorithm that, say for performance reasons, must resist typical normalization/refactoring. Even then, you can easily place an overview of the algorithm in the documentation (or reference a whitepaper), and again remove most of your inline comments.

    As for function-point comments/documentation, I suggest something like Javadoc, C#'s Intellidoc, or some similar platform like doxygen, although if you're manly or insane enough, you can always maintain the documentation separate from the code.
  • by Mr. Slippery ( 47854 ) <tms&infamous,net> on Monday January 09, 2006 @02:43PM (#14429345) Homepage
    that comments are not necessary for clarity and can be dangerous if not kept up to date

    If you can't keep comments up to date in the code you're responsbile for, you're not competent to be responsbile for the code.

    There shouldn't be any debate on the need for documentation. Document your code or hit the road. The only issue is where it goes, in separate docs or in comment blocks. (Doxygen and similar systems make it easy to generate separate docs from comment blocks. Recommended.)

    Code reviews are the best enforcement - if you go in and everyone's asking "what the hell does this block do???", you need to comment it.

  • by gnovos ( 447128 ) <gnovos@ c h i p p e d . net> on Monday January 09, 2006 @02:52PM (#14429440) Homepage Journal
    Even if you're the best normalizer/refactorer (is "refactorer" a word?) in the world, you had better explain what a function or method or class or aspect or (etc..) does, how it's used, and what the expected results are, or you have made code that is a nightmare to maintain.

    That is what your automated tests are for! No comment in the world is better than a test showing exactly how a method works, what expected inputs and outputs are, and *proving* that what you think it should do is what it actually does. The great thing about proper automated tests, they can NEVER go out of date and still pass.
  • Re:Tech Reviews (Score:1, Insightful)

    by Anonymous Coward on Monday January 09, 2006 @02:58PM (#14429482)
    Agreed. Have a competant engineer give it a lookover.

    A few other points:
    Don't confuse comments and design documents.

    Focus on the "why" -- the code itself is the "how." If something seems nonintuitive, describe why you made that decision. Your goal is to get the reader to the same place in your engineering that allowed you to solve the problem and describe the trade-offs. If you have to leave a "popcorn-trail" of ideas you tried, do so. Spending a week debugging to understand the interactions of a complex system should be done once, then described so that the next person doesn't have to.

    Mandatory "flower box" comment blocks at the top of every function are annoying, a waste of time, and a liability. If they exist at the top of every function, then the important comments explaining difficult-to-understand sections get lost in the "noise" of the comments for trivial functions.
    Comments are a liability if you work on a regulated or validated system (think pharma, air traffic control, banking, missile guidance, etc. or any other system where life & fortunes are involved) -- failure to update the comments means the system is out of compliance and a simple change or refactoring turns into a huge time-waster as you go about changing dozens of trivial comment blocks to reflect a new layering or ownership structure.

    Which brings me to the final point: if a block of code is complex enough to need 1) a comment, and 2) a big comment to explain its inner workings, then you probably should refactor and simplify.
  • Like a math proof (Score:5, Insightful)

    by Metasquares ( 555685 ) <slashdot.metasquared@com> on Monday January 09, 2006 @03:21PM (#14429687) Homepage
    Code, like a math proof, is written in a specialized language that people outside of the field are unlikely to understand well.

    Try removing all text from a sufficiently complex math proof, leaving only the mathematical notation, and see if you can still figure out what the mathematician is doing.

    Now try to publish a paper like that.

    No matter how amazing your results, such a proof will not be accepted by the mathematical community. I've run across some very good papers that were discarded because no one, including the author, could understand what all that math was supposed to *do* anymore.

    You should be writing code the same way as you'd write a good proof. You don't need to explain why 1+1=2, but you definitely do not want to skip over critical parts of a proof that are necessary to understand before reaching the conclusion.
  • by anomalous cohort ( 704239 ) on Monday January 09, 2006 @03:33PM (#14429792) Homepage Journal

    I see your point regarding using source code control for change comments. The issue that I have run into putting change comments in the code itself is one that also happens over time and multiple changes.

    Here is an example, let's say you change line 188 to fix defect 2287. Next week, another developer needs to change the same line to fix defect 3012. Does that developer append on to your comment or overwrite your comment? What if the developer completely changed line 188 so that your changes were lost?

    I guess that there is no perfect answer so you end up putting change comments in both the code and in the CVS (or similar) system. The downside of that is the wasted resources and potential for error in duplicitous effort.

  • by ianezz ( 31449 ) on Monday January 09, 2006 @04:39PM (#14430377) Homepage
    On the other hand, with commented code they are dealing with two similar but distinct things

    IMHO, the point of comments is not to tell other how things are done, but why they have been done in that specific way. No amount of code can tell you that.

  • by WGR ( 32993 ) on Monday January 09, 2006 @05:24PM (#14430819) Journal
    In a proper software project, comments are written before the code so they should not be written by the coder. They should reflect the block of the system design that the routine implements, the assumptions made during design etc. It should capture the design so a maintainer can avoid changing the design unintentionally.

    A comment should be there to tell a future maintainer why this code exists, what was the intent and its reason for existence. It does not exist to tell how the routine is implemented, so it should seldom have action verbs.

    The other useful kind of comment is the expansion of variable type declaration that describes the constraints on a variable that are not expressible in code.

  • by metamatic ( 202216 ) on Monday January 09, 2006 @08:29PM (#14432175) Homepage Journal
    All projects, no matter how simple, require comments.

    The comment (or documentation) defines the supported API for the method or function. It is effectively the informal contract between the person writing the code and the person calling it.

    The importance of the design contract is that it allows you to refactor code effectively, rather than having to reproduce every single side effect and internal detail of the code in order to avoid unknown amounts of breakage elsewhere.

    And I'm with the previous guy in the thread. If you don't understand why all functions need comments, you shouldn't be writing anything even remotely important.

    And yes, even code you write for yourself should be commented, so that you can come back to it a year later and refactor.

    For example, take a very simple piece of code: something in a math library to add two vectors together. Suppose you implement it, and your initial implementation is generic and happens to work with complex numbers, rationals, dates, even strings. Well, that's great, but then you profile and discover it's a major bottleneck in your 3D graphics application. You want to refactor it to a high speed piece of inline assembler. You only intended to use the code for vectors of floats--but if you have no design contract, people might be using the routine with all kinds of data types, because it happened to give the result they wanted—and your hopes of a quick and easy refactoring are dashed. You end up having to define a new fastfloatvectoradd(), replace calls all over your code, and maybe end up with the original add() as dead code as far as your application is concerned.
  • by TechieHermit ( 944255 ) on Tuesday January 10, 2006 @01:44AM (#14433602) Journal
    How to comment your project and thoroughly preserve your sanity:

    1. Ignore any standards anyone tries to force on you. Mostly such people are full of hot air, playing a role instead of just BEING a programmer. Things don't have to be buttoned-down. So, ignore the anal retentives and RELAX.

    2. Start sneaking around. Gather up everything you can get your hands on, from original user specs to whatever else. Everything you can beg, borrow, or steal, put in a folder in your desk. When you have some free time, digest it and produce short, easy-to-understand summaries. And, summarize EVERYTHING: business rules, expectations, requirements, EVERYTHING. A short, clearly written summary is worth ten pounds of worthless suit-speak memos.

    3. As you code, start each chunk of code (function, procedure, class, whatever) with a brief paragraph explaining, in your own words, what the purpose of the code is. Just briefly say "this is what I'm about to do, and this is why". Be brief, but specific. Mention anything weird, like odd parameters or whatever. If you have to return a weird string because Joe the Programmer is expecting it, explain it (without being cruel).

    4. Within your code, use self-documenting variables and make sure your indentation, etc (style) is clear and easy to read. I know I bitched about "standards" but it doesn't hurt to read a short book like "the Elements of Java Style". It's a good book. Make your code clean and easy on the eyes. It only takes a minute. USE WHITESPACE!!! Don't clump everything together like a core dump, add some extra lines here and there. A carriage return is only a byte (two if you're on Windows). It ain't gonna kill you.

    5. Whenever you do anything in your code that is non-obvious, like testing a column you got out of a database because there's junk data in there sometimes, EXPLAIN it. Just take a couple of lines to say "The import process sometimes sticks garbage in this variable, so we're doing a sanity check on it". You don't have to comment every single thing you do, but comment everything NON-OBVIOUS you do.

    And, that's about it. I think it's as easy as that. There's no need for company-wide training, or workshops, or any of that stuff. Just a little common sense, and a little effort, and your code's clear to everyone.

  • by JCOTTON ( 775912 ) on Tuesday January 10, 2006 @10:57PM (#14442829) Homepage Journal
    Ninty percent of my work when working on old programs is TRYING TO FIGGUR OUT THE DATA STRUCTURES. Not the code. The Data.
    How about the 25 different letters used in the field cryptically named "F-STATUS"? OR a date in a field named "D-Date"?
    Document your DATA structures you code-monkeys!
  • by B1 ( 86803 ) on Wednesday January 11, 2006 @03:48PM (#14448106)
    Replaceable you must be, or promoted you won't.

He has not acquired a fortune; the fortune has acquired him. -- Bion

Working...