Follow Slashdot stories on Twitter

 



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:
  • We just got rid of our out-of-date function headers and replaced them with doxygen-style comments. The function parameters, return values and called-by / calls information will now stay up to date, and the html reference output is handy.
    • Re:doxygen (Score:3, Informative)

      by baadger ( 764884 )
      Doxygen [stack.nl] is a documentation system for C++, C, Java, Objective-C, Python, IDL (Corba and Microsoft flavors) and to some extent PHP, C#, and D.

      No Perl? :(
    • Re:doxygen (Score:3, Informative)

      by Randolpho ( 628485 )
      Doxygen is nice because it standardizes a particular commentation style over multiple languages, so that whatever you use for a project (or within a project), you comment in roughly the same way, using the same commands, etc.

      Personally, however, I very much prefer the xml-oriented way of doing it found in Javadoc and .NET's comment/documentation scheme.
    • Heh.

      I once suggested this, at least for new code, at a former employer in Canada, was backed up by all other devs who would have to use it, and got the ideas shot down by our boss because he could not see the value in it over the cost of learning a new way to annotate code to be doxygen-friendly.

      Sigh.

      I didn't stay there very long.

  • by voice_of_all_reason ( 926702 ) on Monday January 09, 2006 @12:36PM (#14428072)
    Never comment your code. That way everyone needs to ask you for a fix when thinks break. Think of it as "employment insurance..."
    • No, feel free to comment your code (random gibberish works fine). But whatever you do, do not *read* comments in code and expect them to have any bearing on reality. Even if the comments accurately describe what a program was written to do (rare), someone will have changed the code and not the comments, or the comments and not the code. Save yourself a lot of time and asprin; if you want to know what the code does, read the code.
  • Documentation (Score:3, Informative)

    by bloodredsun ( 826017 ) <martin@nosPam.bloodredsun.com> on Monday January 09, 2006 @12:37PM (#14428083) Journal

    A brief decription of the object/class and then simple comments on any methods. That's a minimum but I would also go for single line comments for conceptually difficult peices of code that you know you will forget in a couple of weeks. Not overly rigorous but easy enough that people do follow it.

    A good model for me would be the Java SDK docs and the javadocs tool but that's just me.

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

        If you fix a minor bug, and a week later you realize it's created a major bug, but in the meantime eight dozen commits have been made by your team, it's not alw

        • 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?

      • Re:Documentation (Score:3, Interesting)

        by dkf ( 304284 )
        An example of a useless comment:

        // Increment rc

        An example of a more useful comment:

        // Bump the reference count

        An example of a much more useful comment:

        // Bump the refcount to stop premature deallocation during the recursive call

        An example of an enormously useful comment:

        /* Bump the refcount to stop premature deallocation during the recursive call. [Bug 122345].
        * Watch out here, the fooble compiler V7 has a tendency to reorder instructions wrongly
        * so the obvious optimization results in a bizarre cras

  • The problem with standards is they confound things and treat them similarly. Each [software] project has different goals, expected lifetimes, maintainability and communications concerns. And sometimes subsections are different.

    About the only thing a good standard will do is present options, advantages and disadvantages, and require that an explicit decision be made after appropriate discussion.

  • 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 oni ( 41625 ) on Monday January 09, 2006 @12:57PM (#14428282) Homepage
      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.

      Spot on!

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

      *stands up and cheers*

      I totally agree. You can't take someone who is, frankly, lazy and selfish - and that's what we're talking about here. Anybody can write code. When you write a comment, you are doing more than coding, you are developing a product, you are making sure that product is maintainable. You are helping people who will come after you, maybe years later, people you'll never meet. People who flat refuse to think that way are lazy and selfish - you can't take someone like that and make them comply. They are worthless. Just fire them.

      You need a business culture that values documentation. You need people who have maintained someone else's code. Those kind of people understand and care. The kind of people who have only ever written new stuff don't get it. They don't understand why this is important. They don't realize that the wiz-bang program they wrote today will have to be thrown away in a year or two when the boss asks for just one little button to be added. It will have to be thrown away because it'll be cheaper to rewrite it than to decode it and add the button. Some people just don't get that.

      Look, commenting is not rocket science. You don't need strict rules. A comment is a communication with someone in the future. It's like a time capsule. You just need to comment things when it's reasonable to think that a person looking at the code might need help. You don't need comments like //add one to x and store it in x. But you might need a comment like, //increment x because this procedure pushs the stack.

      In an interview with a prospective programmer ask the following question: "what is the most expensive part of the development lifecycle" If they say anything else except maintenance, don't give them a job. They don't get it. They aren't going to do it.

      I also want to add something to the story, where it says this:
      dictating the formatting of the code (an issue on which there is widespread agreement)

      I was thinking, "yeah right, there is widespread agreement on the idea, but when you sit down and try to do it you'll find widespread disagreement." Everybody likes the idea of forcing the other programmers to write code the same way that you do. Nobody likes the idea of having to write code a certain way. Where I work, there was widespread agreement too, but we never got past the issue of capitalizing the first letter of functions. Seriously.

      If I had to do it again, I would get some premade coding standards. Creating your own is too hard.

    • 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"

      I call bullshit. Visual Studio is easily capable of doing a find-and-replace over the entire project (try CTRL-H). It shouldn't have taken you more than 30 seconds to fix this problem. If you spent the entire day "re-factoring" then you obviously had more serious problems than a simple deviation

    • The company I work for has a "standard" that says "every method you write must have a comment".
      So our code has hundreds of methods called things like getFoo() and setFoo() with comments like "this returns the value of foo" or " this sets the value of foo".
      By the time you've written all these useless comments, you're too tired to write a single useful comment that explains how the code works.

      In any case, code is always obvious when you've writing it. So it's hard to know what comment would be needed to

      • 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, s

  • Are you serious? (Score:5, Interesting)

    by zhobson ( 22730 ) on Monday January 09, 2006 @12:41PM (#14428138) Homepage
    If your code is not commented it's not complete. My advice is to fire every developer that doesn't think that comments are necessary.
    • Ops, you just lost all the developers who manage to write code that is so clear it doesn't need comments.
      • 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 gnovos ( 447128 )
          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 )
            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 algorit
            • by gnovos ( 447128 )
              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.
              • Don't assume that everyone who will read the code will want to figure out what the tests are doing as well.
                • Of course they will, if they want to use it properly. Why assume somone will read comments but not read the tests?
                  • The same reason that some people only read half of a long email: They think they've read "enough" to get the "gist" of it, even if they miss something like "your default password is your last name" at the bottom. Ideally, you probably want an explanation of what the code does as near to the code itself as possible.

                    I had a friend who used to refer us to his tests whenever we had a question about his code. They were his only form of documentation. He didn't believe in submitting the tests with the program its
                    • He didn't believe in submitting the tests with the program itself or sharing them with other developers, so no one could ever understand what he was doing.

                      Come on, there is no way any sort of documentation could have helped this kind of problem... If he isn't willing to submit his tests, what chance is there he'll submit his documentation?
              • Re:Are you serious? (Score:3, Interesting)

                by AuMatar ( 183847 )
                And here is one of the reasons the agile method people get so much wrong. Automatic tests are not documentation, by any means. They do not prove that code is correct, or bug free. A test proves that for some input, a certain output was generated. Thats it. It doesn't explain why that output was generated, why that case was important, what other cases might be important, how those test cases were chosen, or explain the logic used to generate that output. For that you need documentation- either in code
                • And here is one of the reasons the agile method people get so much wrong. Automatic tests are not documentation, by any means. They do not prove that code is correct, or bug free. A test proves that for some input, a certain output was generated. Thats it. It doesn't explain why that output was generated, why that case was important, what other cases might be important, how those test cases were chosen, or explain the logic used to generate that output. For that you need documentation- either in code or out
                  • Documentation can absolutly NOT tell you "why that output was generated, why that case was important, what other cases might be important, how those test cases were chosen, or explain the logic used to generate that output".

                    No, thats ABSOLUTELY what documentation tells you. It tells you what a function is for, and what the expected output is. Your test cases should be documented as well, wether they be automatic or not- why was this test case chosen (corner case? random pick? check some bug we just fix

                    • Re:Are you serious? (Score:3, Interesting)

                      by gnovos ( 447128 )
                      No, thats ABSOLUTELY what documentation tells you. It tells you what a function is for, and what the expected output is.

                      Does your function exist for a single purpose? Is it ever going to be reused? The problem with saying what a function is FOR (what you see in documentation) as opposed to what it DOES (which you see in code and tests) is that it assumes many thing that may or may not be correct. It also will breed duplication, as you may implement one method fome one "purpose" and another method for an
                    • And when this happens, the FIRST thing you do is change the documentation to reflect that. If you don't, you aren't doing your job.

                      I Am A Useless Programmer, but... :p

                      I would imagine it is very easy to either not update documentation/comments, or to update them incorrectly. It would be much harder to make that mistake with automated testing. Comments don't fail, tests do :).

                      But if your workplace is that sloppy, agile methods will be even worse-if you have devs who are so incompetent that they can

                    • Oh sure, its possible to forget or make mistakes. Then the next person comes around and sees they don't match. One of them is wrong. Figure out which and fix it.

                      As for not getting automated tests wrong- boy would you be surprised. Its actually quite easy, and when you do it can be difficult to debug- you look everywhere else for the problem first "because it passed the tests". I don't trust the tests much due to that.
                    • Does your function exist for a single purpose? Is it ever going to be reused? The problem with saying what a function is FOR (what you see in documentation) as opposed to what it DOES (which you see in code and tests) is that it assumes many thing that may or may not be correct. It also will breed duplication, as you may implement one method fome one "purpose" and another method for another "purpose" where actually they are exactly the same code, just with different names.

                      Why yes, yes they do. Thats pretty

              • Automated tests do not grant context. Only non-structured narrative documentation can fully explain the purpose and use of a block of code.
                • Automated tests do not grant context. Only non-structured narrative documentation can fully explain the purpose and use of a block of code.

                  Do you want your code to me modular and reusable? If so, what good is context?
                  • Good context for modular and reusable code include things like the the purpose for class. Is the class a custom GUI control, a data object, a control/worker object? What does the data represent? What does the worker object do? What does your control allow users to do?

                    Of course, that's modular-level, but the same must be done on the method level and lower. What does this method do? Does it animate a portion of the control in some way? Does it maniplate the data to a new state? What do the arguments represent
                    • Good context for modular and reusable code include things like the the purpose for class. Is the class a custom GUI control, a data object, a control/worker object? What does the data represent? What does the worker object do? What does your control allow users to do?

                      Of course, that's modular-level, but the same must be done on the method level and lower. What does this method do? Does it animate a portion of the control in some way? Does it maniplate the data to a new state? What do the arguments represent
                    • What seems to not make it across is that anything that cannot be expressed in code cannot be expressed in documentation either.

                      Do you really think that? However great your code is, it inevitably is going to contain assumptions and higher-level structure; for readers to fully understand the code, they have to know about them, and simple english text is a concise and powerful way of communicating that information.

                      An example might be a comment saying: "This code uses algorithm X, which was picked because it h
                    • What seems to not make it across is that anything that cannot be expressed in code cannot be expressed in documentation either.


                      So how do you name your functions and variables to convey the information to convey the information that:

                      "We have used an O(n^2) algorithm here because the input data is highly structured and the O(n^2) algorithm will actually be faster then the usual O(n log n) algorithm."

                      ?
          • In 21 years of coding, I have yet to see a project so simple that comments were not required. If you don't know how to write a comment, you have no business coding. If you cannot take the time to comment, you have no business coding. If you think comments are stupid, you have no business coding.
            • Re:Are you serious? (Score:3, Interesting)

              by gnovos ( 447128 )
              In 21 years of coding, I have yet to see a project so simple that comments were not required. If you don't know how to write a comment, you have no business coding. If you cannot take the time to comment, you have no business coding. If you think comments are stupid, you have no business coding.

              In your 21 years have you ever seen a project built and run for several years, adding new features every week, never slip a single deadline, all without a single bug of any kind making it into production? I've two s
          • Re:Are you serious? (Score:5, Interesting)

            by Anonymous Brave Guy ( 457657 ) on Monday January 09, 2006 @08:02PM (#14432025)

            I've read all the other replies to this comment at the time of writing, and it's a fascinating discussion. Initially I thought you were just a troll, given that you claim to have produced completely bug-free projects and never to use comments, but now I think you've just had a little too much of the agile kool-aid, so I'll address some recurring points one by one.

            On the trustworthiness of documentation (comments, paper or otherwise): no, you shouldn't absolutely trust them above all else. The final authority about what is happening is always the code. But if your documentation is any good at all, it's not the sort of thing that you refer to last, it's the sort of thing you refer to first. The documentation isn't the implementation, it's just a map of it, telling you what should be happening. Comments are the guidebook, highlighting the major attractions as you reach them and pointing out the subtleties that aren't apparent at first.

            The most successful projects I've worked on have relatively little documentation, but it's well-written and useful. My current project, for example, has perhaps 200,000 lines of code. We have maybe 20-30 reference documents, each electronic and running only to a handful of pages, describing the overall design of the major subsystems and broadly speaking how they're intended to interact. The implementation speaks for itself, with explicit comments generally reserved for things like dividing up longer functions into logical sections, citing references that describe how the algorithm works (from our own documentation or otherwise), or clarifying intent on the odd occasion that the code isn't completely self-documenting. Notice that none of these things, except possibly the last, are likely to need amending just because you change the code.

            You also seem to be arguing that it is unnecessary to maintain any sort of coherent overall design in an "agile" project, because your automated tests guarantee correctness. Sorry, but I think you're seriously misguided on both counts.

            Automated tests are a useful mechanism for increasing reliability, but they're no substitute for a logical design, code review, or any of the other things that contribute to code quality. Unless your tests cover every code path with every conceivable set of inputs, they simply can't do that. My current project has an automated test suite that runs to 1,000s of tests, and yes, they're very useful for spotting major errors and regressions, but they still don't catch anything like all the bugs. No test suite for a large scale application ever has 100% coverage. And even if the test suite does pass in its entirety, it's no guarantee that you got the answer the way you intended and all your code is working. Two wrongs do make a right, if you incorrectly multiplied by -1 twice.

            As for the presence or otherwise of an over-arching design, what you say is true: your code and tests are indeed guaranteed to give you the results your tests say you will get for as long as the tests pass. Of course, that doesn't mean that you can easily extend, modify or reuse that code. In fact, my experience of projects developed with the methodology you describe is that they're written very quickly, but rapidly become almost unmaintainable; someone will find a bug that your tests didn't, and you'll dutifully write a new test, and then it will take you a week to refactor this and elevate that until you can get the test to pass without breaking anything else. The guys who had a carefully planned, well-maintained and systematic design would probably have fixed that bug in five minutes, and without breaking anything else, because the problem would have been localised, easy to track down, and unable to adversely affect other areas of the system.

            Speaking of code reuse, I notice that you're very keen not to bring context into things. I hate to break this to you, but code without context is meaningless, no matter how "reusable" it may be. When context starts to interfere with your reality, a lot of

            • And even then I don't believe you've ever shipped code with no bugs.

              Very intersting reply, and probably very good points for those who are used to a mor traditional form of programming... But this is the key right here, in your last sentence. Most people just don't believe it's possible to ship without bugs whereas I and the other developers where I work wonder how it's possible to ship a product WITH bugs. I have tried to explain too often to others in my profession, and I always get this same response
              • I appreciate the reply, but you still seem to be making the mistake of assuming that the rest of us haven't tried your approach and don't know what we're talking about. Please understand that you are not the only conscientious programmer on the planet, nor are the ideas you advocate particularly original.

                As I mentioned, the project I work on has thousands of automated tests. We write code in small chunks, and run the tests before releasing it. We also have a clear idea of what we're aiming for, courtesy o

          • by metamatic ( 202216 )
            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
      • No such code exists. There are *portions* of code that don't need comments, but the code in general *will*.

        Grab.
      • You aren't commenting your code (else you'd see a lot of "c++; //increment c" stuff); you're commenting your logic.

        Maybe the code is self-documenting, but program logic for any reasonably complex problem is not. I don't care how much you've abstracted it; you still need to show how you're using those abstract pieces to solve the problem you're given. You still need comments.

        If the developers refuse to comment their code on this basis, I'd probably get someone of average intelligence from sales or HR to

      • There's no such thing as code which is so clear it does not need comments. If there's a developer who thinks his is, he needs to have his head removed from his ass.
    • If your code is not commented it's not complete. My advice is to fire every developer that doesn't think that comments are necessary.

      Seriously.

      I code C# for fun, on my own. I still comment, because otherwise when I go to look at it in a year or two, I will have forgotten the reasoning behind some of my decisions.

      I do a bit of it at work too. I'm an engineer there, but a few people in my group use ASP, ASP.NET, and VB.NET to write simple utility apps. Trying to work with their code is a *nightmare* because t
  • dupe? (Score:3, Informative)

    by MalaclypseTheYounger ( 726934 ) on Monday January 09, 2006 @12:43PM (#14428159) Journal
  • 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.

  • Pig Latin (Score:3, Funny)

    by Saeed al-Sahaf ( 665390 ) on Monday January 09, 2006 @12:52PM (#14428233) Homepage
    I use Pig Latin to comment my code. Job security, you know.
  • Seems like you missed a step. First you decide if you're going to use an auto-generated code documentation tool like Doxygen. That alone will dictate the majority of any comment-standard.
  • 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.

    • by Grab ( 126025 ) on Monday January 09, 2006 @02:11PM (#14429024) Homepage
      You're misunderstanding the real purpose of comments.

      If your comment says "Increment i" and the code says "--i" then yes, things are fucked. But the purpose of comments is not to describe *what* the code does but *why* it does it (and occasionally *how* as well if it's not clear, for example if there's some particularly gnarly maths or pointer weirdness involved).

      Anyone writing comments saying *what* their code does what it does needs their code reworked at review - and if they're not on their first job then they need firing.

      Anyone *not* writing comments saying *why* their code does what it does needs their code reworked at review - and if they're not on their first job then they need firing.

      Grab.


      • I agree, to a point. "Why" (and "how") comments are far better than "what" comments, but the fundumental problem still applies. Even "why" comments can obscure bugs:

        i -= 1000 if i > 1000 # We only have room for (and only need) three digits
        --MarkusQ
        • How does that obscure the bug in that line? It makes it much more obvious because you know what they're trying to do.

          • How does that obscure the bug in that line? It makes it much more obvious because you know what they're trying to do.

            Because (and this has been well tested) people tend to read the comment instead of the code. The high tech tests tracked people's eye movements and such, but you can show the same thing by timing how long it takes people to find bugs, or just quizing them afterwards.

            The effect gets more pronounced for larger segments of code. In one example that I recall, half a group of programmers w

    • That's where EIFFEL has an advantage over other languages, it's comments can't disagree with the code. The comments are part of the design by contract methodology that the language enforces. You setup your incoming inputs with an expect statement, then guarentee your outputs with an ensure block. Failing to meet either the expect or ensure conditions throws an exception which you can catch and hadle as needed.
    • 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.

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

  • Tech Reviews (Score:3, Informative)

    by crmartin ( 98227 ) on Monday January 09, 2006 @01:33PM (#14428658)
    The answer (40 years of experience with this) is not to set a standard on how much commenting is needed; it's to have walk-throughs of the code with an intelligent reader who isn't directly involved with the code. If they can read and understand the code, it's enough.

    Look into Fagan reviews [google.com] for details on an effective way to handle this.
  • May I be a sort of voice of reason, of a kind? comments are tasty things which should be used regularly and often. spelling and grammar may not be necesarry to be observed, but in my opinion, I would much rather see roughly one comment fFor every, say, 6 lines of code. I dont mean in exact ratios portioned out like rations .. you could have a whole page or two of comments sometimes which covers 3 pages of other stuff, if it's all somehow convenient. that's cool. And, you know, variables and routines wi
  • simple rule (Score:2, Insightful)

    by outcast36 ( 696132 )
    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.
  • Basically, treat comments like you should credit card debt. Use it rarely, only when you really have to, and try to get rid of it as soon as possible. If you can write the code in a clearer way, one that does not need comments, then do so, ASAP.

    In a perfect world, the ONLY thing that you want to have comments are APIs into closed code (some outward-facing API that you aren't willing to give the source to). Everything else should only have comments when the code is too complex to be understood by reading
  • It SHOULD be hard to understand.

    http://thc.org/root/phun/unmaintain.html [thc.org]

    In all seriousness. I would just enforce "header" comments to a particular style (javadoc..etc). The rest is up to the individual programmer.

    The trouble as pointed out earlier is that programmers/code reveiwer have to be always be updating comments as the code gets updated. This doesn't always happen and is the caused me personally some problems as I took the comment to be right, when clearly they were not. I use comments as a guide now
  • by bill_kress ( 99356 ) on Monday January 09, 2006 @02:05PM (#14428967)
    I keep seeing all these arguments either against commenting or against verbose languages because, supposedly, they slow development.

    Now, Maybe I've just been programming too long and have gotten too good at it, but typing is never ever a slow-point in coding; heck, even learning a new language doesn't slow you down too much!

    The slow part is designing your code correctly so that it's fully factored and as bug-free as you can manage--this takes thought and a bit of time, but no where near as much time as it would take to do the same release with cut & paste (I've seen it many times).

    So I'm trying to figure this out, why are people making these arguments? Is it that for unexperienced people it truly is harder to put comments in with your code? Maybe they don't know how they did their magic and don't want others to figure them out? Maybe they never took a typing class and it truly takes more time to code than think? I'm really at a loss here.

    Oh, and as for the authors question, you have a FANTASTIC opportunity to improve your company tenfold. Take notes of those arguing against commenting. As soon as you've collected all the votes, throw them away and FIRE anyone who was against documentation--they should not be working in any company, at least not as a programmer! If you hired people who understood programming and the development cycle, that question would have never come up.
  • The problem isn't "should we comment" or even "how many comments should there be" -- the problem is actually "what should the comments say" at my work I have seen several different styles of comments and invariably, one type of comment stands out as useful and other comments are mere distractions, at best. Comments should never be used to document how code works. The code itself shows how it works -- or at least it SHOULD. If your code isn't readable, THEN RE-CODE IT! It's not maintanable. I don't car
    • then in the prolog of my program, I have a comment that describes changeflag 01, who made the change, the date of the change, and the location of the document describing the need for the change (bugzilla number, etc). This not only keeps the documentation up to date, but provides a paper trail.

      An alternative approach is to pick a revision control system and teach people how to use it. For example, we use Subversion and can do stuff like:

      $ svn blame RetrieveRemote.py
      ...
      409 jsmith import time
      530 bm

  • I've been programing for most of my life and have only documented about 3 peices of my work where things got so complex, it was making my head hurt. Even then, my comment says "I feel sorry for the next person who has to figure this out..." or "Don't ask what I was thinking here...".

    IMO, if someone comes up and asks for documentation, they need to be fired! They obviously either 1) don't know how to read code and shouldn't be programming; 2) Don't understand the problem the code is trying to solve.

    Cod
    • IMO, if someone comes up and asks for documentation, they need to be fired! They obviously either 1) don't know how to read code and shouldn't be programming; 2) Don't understand the problem the code is trying to solve.

      On the rare occassion that I look at code and can't figure it out, I rewrite it because, obviously, the code sucks.


      Hack Mplayer. Then come back to me.
    • Code is like a foreign language - you either know it or you don't. Comments are for people who don't know it; and if they don't know it, they need to find another job or learn the language.

      To take your analogy of code being a foreign language on step further then, writing a program is somewhat akin to writing a tale. I would therefore liken writing code without comments to writing a story with no naration. Yes, it can work, but a narator works well to expose the underlying purpose of the tale.

      Quite fr

      • Code is like a foreign language - you either know it or you don't. Comments are for people who don't know it; and if they don't know it, they need to find another job or learn the language.

        To take your analogy of code being a foreign language on step further then, writing a program is somewhat akin to writing a tale. I would therefore liken writing code without comments to writing a story with no naration. Yes, it can work, but a narator works well to expose the underlying purpose of the tale.

        An excellent

  • 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

  • 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.
  • What I said earlier (Score:2, Informative)

    by arensb ( 17851 )
    I wrote what I thought was a pretty decent article on comments a while back:
    http://freshmeat.net/articles/view/238/ [freshmeat.net]

    The gist of it is that the source tells you what the code does, and comments tell you what it's supposed to do, why it looks that way, how it connects to other parts of the program, any weird gotchas, and so forth.

    Comments help you zero in on the part of the code you're looking for when you're trying to fix a bug; and they help confirm that the code really does what you think it does.
  • I find code that is littered with comments hard to read. It's like mixing french with english so the french-speaking people can figure out what the english means. This is what code with comments looks like to me:

    /*
    Cette phrase est au sujet de l'opinion de l'auteur de poteau sur le code de programmation de commentaire.
    */
    Comments are bad // montrer une aversion forte
    because they make code more difficult to read.

    Who wants to read something like that?

    (Babelfish used for translations)

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

The Tao is like a glob pattern: used but never used up. It is like the extern void: filled with infinite possibilities.

Working...