Become a fan of Slashdot on Facebook

 



Forgot your password?
typodupeerror
×
Programming IT Technology

How to Write Comments 556

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.
This discussion has been archived. No new comments can be posted.

How to Write Comments

Comments Filter:
  • Back in grade 12 (Score:1, Informative)

    by Data Link Layer ( 743774 ) on Wednesday November 30, 2005 @11:57AM (#14147390)
    There was a final project worth 50% of our final grade (it took 3 months todo) I didn't comment and I fail it.
  • Haiku Commenting? (Score:5, Informative)

    by drewzhrodague ( 606182 ) <drew@nOsPaM.zhrodague.net> on Wednesday November 30, 2005 @11:57AM (#14147394) Homepage Journal
    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.
  • by podz ( 887481 ) on Wednesday November 30, 2005 @11:58AM (#14147415)
    Rob Pike, a former powergeek at ATT&T labs, and a present powergeek at Google, has the following [lysator.liu.se] to say about code commenting. In general, I agree with him.
  • Three Books to Read (Score:3, Informative)

    by CortoMaltese ( 828267 ) on Wednesday November 30, 2005 @12:05PM (#14147494)
    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.)

  • One good reason (Score:3, Informative)

    by Billosaur ( 927319 ) * <wgrotherNO@SPAMoptonline.net> on Wednesday November 30, 2005 @12:11PM (#14147553) Journal

    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.

  • by tehshen ( 794722 ) <tehshen@gmail.com> on Wednesday November 30, 2005 @12:30PM (#14147745)
    In contrast, WardsWiki has a list of how to make it so your code doesn't need comments so often: SelfDocumentingCode [c2.com]
  • Re:Haiku Commenting? (Score:5, Informative)

    by Coryoth ( 254751 ) on Wednesday November 30, 2005 @12:31PM (#14147749) Homepage Journal
    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 [loria.fr] and D [digitalmars.com] support pre and post conditions directly in the code (instead of in comments). Java has JML [iastate.edu] 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 [praxis-his.com] 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 [wayforward.net] 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.
  • by AlvySinger ( 900304 ) on Wednesday November 30, 2005 @12:33PM (#14147767)
    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.
  • by rjstanford ( 69735 ) on Wednesday November 30, 2005 @12:39PM (#14147837) Homepage Journal
    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.
  • Re:Reading (Score:5, Informative)

    by InvalidError ( 771317 ) on Wednesday November 30, 2005 @01:01PM (#14148065)
    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.)
  • by moskrin ( 53287 ) on Wednesday November 30, 2005 @01:42PM (#14148528)
    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.
  • Re:Reading (Score:5, Informative)

    by gstoddart ( 321705 ) on Wednesday November 30, 2005 @02:20PM (#14148938) Homepage
    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 [big.or.jp].

  • Re:Reading (Score:2, Informative)

    by Dachannien ( 617929 ) on Wednesday November 30, 2005 @02:35PM (#14149087)
    Six syllables in
    The first line of your haiku
    Also, winter sucks.
  • Re:Haiku Commenting? (Score:3, Informative)

    by Coryoth ( 254751 ) on Wednesday November 30, 2005 @03:06PM (#14149412) Homepage Journal
    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.
  • Re:lazy programmers (Score:2, Informative)

    by reclusivemonkey ( 703154 ) on Wednesday November 30, 2005 @04:06PM (#14149884)
    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 :-)
  • SQLite sourcecode (Score:1, Informative)

    by Anonymous Coward on Wednesday November 30, 2005 @04:57PM (#14150359)
    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.
  • Re:Reading (Score:3, Informative)

    by dcam ( 615646 ) <david AT uberconcept DOT com> on Wednesday November 30, 2005 @05:31PM (#14150743) Homepage
    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

    }
  • by DeafByBeheading ( 881815 ) on Thursday December 01, 2005 @12:40AM (#14153904) Journal
    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>

A morsel of genuine history is a thing so rare as to be always valuable. -- Thomas Jefferson

Working...