Slashdot Mirror


How to Write Comments

Denis Krukovsky writes "Should I write comments? What is a good comment? Is it possible to comment a class in 5 minutes? See " Everybody knows that good code is self documenting- which is why my prof in college demanded we write in Ada. I instead suggest commenting in haiku.

18 of 556 comments (clear)

  1. Back in grade 12 by Data+Link+Layer · · Score: 1, Informative

    There was a final project worth 50% of our final grade (it took 3 months todo) I didn't comment and I fail it.

  2. Haiku Commenting? by drewzhrodague · · Score: 4, Informative

    Actually, that would give some of us that have to review code something interesting to look at. Those that think code is self-commenting, forget that there are people like me, who aren't great programmers, who have to either fix your bugs, make simple modifications, or add really simple things. When there aren't comments, it is hard to figure out what parts of what do which.

    --
    Zhrodague.net - I do projects and stuff too.
    1. Re:Haiku Commenting? by Coryoth · · Score: 4, Informative

      What parts do what should be clear from the names of function calls and variables, but whenever a function becomes longer than something really short, yes, it needs comments describing what happens where. If a function does something complicated, it's worth starting with a comment describing pre- and post conditions.

      Now there is an excellent idea! It doesn't take a lot of effort - you should be able to come up with some basic constraints on inputs and outputs if you have any decent idea of what the function does - but it is very helpful documentation to anyone else, particularly for people who have to call the function (as it clerly delimits exactly what they need to provide, and exactly what they can expect to get back). Better yet, as long as you use a system that supports it you can get a whole lot of benefits in terms of automated checking and debugging of your code, saving you a lot of effort later.

      Eiffel and D support pre and post conditions directly in the code (instead of in comments). Java has JML which is a syntax for writing pre and post conditions in comments, as well as some tools to do extra checking, add runtime checks to your code (or not) based on the conditions, write the conditions into JavaDoc properly, and automatically generate JUnit tests based on the conditions. If you program in Ada there's SPARK which supports pre and post conditions as comments as well as a range of other annotations, and provides extremely powerful tools to do extensive static checking and analysis and even generate automatically simplied proof obligations based on your annotations. If you program in Python there's PyContract which allows you to write pre and post conditions into docstrings and switch on or off runtime checking of those contracts. I expect there are plenty more, so hopefully other people can mention those.

      Jedidiah.

    2. Re:Haiku Commenting? by Coryoth · · Score: 2, Informative

      Perl has a similar thing in the Class::Contract module, which makes it easy to design by contract in Perl. It's actually pretty slick...

      I didn't know about that one (mostly because I haven't really done any Perl programming in quite a while) but you're right, it is pretty slick. I like it. definitely a must next time I end up doing any OO Perl.

      Assertions have long been a part of C and C++ programming, of course, but that's not really designing by contract, so much as performing error checking. These are different things, though certainly the latter is a superset of the former.

      My real gripe with assertions as opposed to proper DbC is that it doesn't behave nicely with respect to subtyping/inheritance, or automatic inclusion in documentation, but that's more a matter of ease of use and niceness than actual functionality. As you say, it still does job.

      Jedidiah.

  3. Check out Rob Pike's thoughts on code commenting by podz · · Score: 5, Informative

    Rob Pike, a former powergeek at ATT&T labs, and a present powergeek at Google, has the following to say about code commenting. In general, I agree with him.

  4. Three Books to Read by CortoMaltese · · Score: 3, Informative
    Three pretty good books that have insightful views on how to write readable code and comment it appropriately:

    In short, they all suggest writing readable code is more important than commenting spaghetti, but there are also good points on commenting. (Can't be bothered to copy-paste them here, though, see for yourself.)

    1. Re:Three Books to Read by tehshen · · Score: 2, Informative

      In contrast, WardsWiki has a list of how to make it so your code doesn't need comments so often: SelfDocumentingCode

      --
      Guy asked me for a quarter for a cup of coffee. So I bit him.
  5. One good reason by Billosaur · · Score: 2, Informative

    You should write comments because some day you're not going to be doing your job anymore, perhaps because you started your own rock band, or won the lottery, or the company decided they could get someone cheaper to do your work. In any case, some unfortunate soul (and I've been this person more than once) has to come in and maintain and expand your code. And in most cases we're bright and we know our languages pretty well, but we can be a little slow on the uptake. In the end, we stare at your code and ask, simply: What the freak is going on here?!?!? Because we are not mind readers, and if we were, we probably wouldn't want to touch your mind because... ewwwwwwwww!

    Does this mean you have to do this?:

    my $i = 0; # initialize variable $i

    No! We're not retarded... we think. But if it's not trivially obvious what you're doing somewhere in your code, please feel free to let us in on it. We would appreciate it.

    --
    GetOuttaMySpace - The Anti-Social Network
  6. Closely linked with good code by AlvySinger · · Score: 2, Informative

    It's pointless writing "good" comments on bad code. Write clear obvious code that doesn't rely on needless tricks or language side-effects.

    Layout is important but don't get obessive. You'd write prose using paragraphs, use whitespace in code.

    Good comments are hard because, like code, bad comments are very easy. Don't describe what's obvious from the code. Why is better than how. Don't spend ten lines describing a pattern when you can refer it by name.

    Don't add redundant comments (and this is from someone who writes more than my peers). Twenty lines of boiler-plate for each method is pointless. If there's a need for a detailed change history then your source-control should provide this. If the code requires heavy detail try refactoring it to make the code clearer.

    Simple metrics are difficult but look at your code without comments and imagine what'd be useful if your coming at it blind. What would you want to see? (Try this with a random sample of colleagues code. Typically - from experience - you won't have to spend too long removing comments because there won't be any.)

    And the difficult bit: make sure you're in a culture that values comments and documentation. It's pointless crafting detail now if some future developer will ignore them or not maintain them.

    Finally, none of this is exact. Everything about can be argued. Get some literature (McConnell, Brooks, etc.) and learn from this too. Use what the situation demands, don't apply things where they're not warranted.

  7. Re:The why not the how by rjstanford · · Score: 5, Informative

    Sorry, but you happened to hit on one of my pet-peeves with non-self-descriptive code. I do agree with your suggestions, mind you, but I see it all the time: functions describing how they work, not what they do. Sorry to pick on you, but in this case why not take:

    public bool CheckSmsValue(Account smsAccount)
    {

    And instead say:

    public bool isSmsValueAccurate(Account smsAccount)
    {

    That way, anyone who glances at the call will know what the function does. In fact, the first one could be checking for existance, non-existance, accuracy, threshold, who knows? Heck, its exactly the kind of function that I could see being called in many different places by people expecting it to be checking different things. Or coder1 adds it in expecting it to check for "positive" as well as whatever else, months later coder2 realizes that it doesn't and adds the "extra check" into it - its a check function, after all, right? And then coder3's code in some far-away place suddenly starts failing because he didn't want that check in the function.

    A good name should be an implict contract. The function above should, by that definition, return "true" if it did at least "check" the SmsValue, and "false" if it didn't bother to... not quite what the original intent was. Probably.

    Phew. Sorry for the long-windedness.

    --
    You're special forces then? That's great! I just love your olympics!
  8. Re:Reading by InvalidError · · Score: 4, Informative

    Same for me.

    Having one-liner comments all over the place makes comment maintenance more troublesome and can distract from actual comprehension of what is going on while reading the code, particularly when there are bits of orphaned antique leftover comments. A single comment blob before a function or large code sections tells the reader about the spirit of code to come without interfering with reading beyond there and makes it easier to maintain comment coherence when changes are made.

    For more convoluted code, I often add blobs before major loop/switch/etc. too - adding comments while I write these things takes less time than what it may take me to re-read the code until I remember exactly what it does and how. (inputs, outputs, side-effects, etc.)

  9. Re:Humour in the Linux kernel - on fire by moskrin · · Score: 2, Informative

    As I understand it, the "on fire" entry in the printer status indicates when a line printer has a paper jam and is still online, thus potentially generating enough heat to *actually* catch fire... or so I've been told.

  10. Re:Reading by gstoddart · · Score: 4, Informative
    My haiku is rotten
    I hang my head in sorrow
    Forgot the season.

    For anyone not getting this, a traditional Haiku always contained references to the season.

    --
    Lost at C:>. Found at C.
  11. Re:Reading by Dachannien · · Score: 1, Informative

    Six syllables in
    The first line of your haiku
    Also, winter sucks.

  12. Re:lazy programmers by reclusivemonkey · · Score: 2, Informative

    Back before UML was a common thing, I used to 'write' my code in comments and stubs, as a design. After I could read through the code as a narrative of what my app/service/dll did, I would actually fill in the stubs to make it work. This ended up saving me a lot of time in the long run, as I didn't really have much refactoring work to do while coding.

    For a non-programmer writing VBA at work, this has been by far the most useful comment to me. Thanks :-)

  13. SQLite sourcecode by Anonymous Coward · · Score: 1, Informative

    Anybody who thinks we should rely on self-evident code instead of comments should look at the SQLite sourcecode. Every function has a clear, detailed comment which says nothing about how the function works, but does tell how it fits into the overall program. No amount of code restructuring and variable renaming will do what those comments do. It's the easiest-to-understand opensource code I've ever seen.

  14. Re:Reading by dcam · · Score: 2, Informative

    I'd largely agree with this.

    One helpful practice I picked up (see Code Complete, Steve McConnell) was to design functions in advance and use the design a the comments.

    eg
    function foo()
    {
     
    // open input file
     
    // parse into local variables
     
    // print result

    }

    --
    meh
  15. Re:Question for all the coders out there.. by DeafByBeheading · · Score: 2, Informative
    With 1280x1024 being a relatively common display resolution used by developers these days I don't think it is such a big deal to have an extra line for the braces


    <disgruntled 1024x768 coder>
    How big a deal it is depends a lot on the kind of code you're writing. If you've got lots of small ifs, tight loops, and small functions, the braces *do* take up a significant chunk of screen real estate.
    </disgruntled 1024x768 coder>
    --
    Telltale Games: Bone, Sam and Max