Stories
Slash Boxes
Comments

News for nerds, stuff that matters

Slashdot Log In

Log In

[ Create a new account ]

What is Well-Commented Code?

Posted by Cliff on Mon May 20, 2002 03:16 AM
from the inlined-internal-documentation dept.
WannaBeGeekGirl queries: "What exactly is well-commented code anyway? Can anyone suggest resources with insight into writing better comments and making code more readable? After about six years in the software development industry I've seen my share of other people's code. I seem to spend a lot of time wishing the code had better (sometimes _any_) comments. The comments can be frustrating to me for different reasons: too vague, too specific, incoherent, pointing out the obvious while leaving the non-obvious to my imagination, or just plain incorrect. Poorly or mysteriously named variables and methods can be just as confusing. In a perfect world everyone would follow some sort of coding standards, and hopefully those standards would enforce useful comments. Until then, any suggestions for what you, as a programmer, consider to be good/useful/practical comments? Any suggestions for what to avoid? Also, I usually work with C++ so any resources/comments specific to that language would be too."
This discussion has been archived. No new comments can be posted.
What is Well-Commented Code? | Log In/Create an Account | Top | 826 comments (Spill at 50!) | Index Only | Search Discussion
Display Options Threshold:
The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
(1) | 2 | 3
  • Variable Names by ludey (Score:1) Monday May 20 2002, @03:20AM
    • Re:Variable Names by alpha1125 (Score:2) Monday May 20 2002, @03:38AM
    • Re:Variable Names (Score:4, Insightful)

      by gazbo (517111) on Monday May 20 2002, @03:39AM (#3548870)
      I experience code from others who have this problem, and frankly it pisses me off. Not meaning to flame you, but what seems creative and amusing at the time stays in the source, and becomes stupid and annoying later.

      The same goes for 'amusing' comments in the code, or CVS logs.

      For your sake in the future, and your coworkers' sake now, please stop it.

      PS. Did I mention how fucking annoying it is?

      [ Parent ]
    • Re:Variable Names (Score:5, Insightful)

      by emag (4640) <slashdot&gurski,org> on Monday May 20 2002, @03:58AM (#3548937) Homepage
      On one of the last projects I worked on, the specs we received from the customer were horrendous. Actually, it wasn't the customer themselves who had done the specs, but another contracting firm. Spending 5 months on the project, and finding repeated errors in the "data maps" (it was apparently too bloody difficult for us to be supplied with a schema for the DBs we were supposed to be accessing and updating), I'd finally had enough.

      Querying the DBs directly showed that the data maps were works of pure fantasy in several spots, or would lead to outright data loss if followed precisely. In a fit of pure...creativity...I ended up setting a "$workAroundFuckups" variable, and in the sections where it was needed, had a false evaluation do precisely what thee datamaps said, which would corrupt data. If the variable was true (ie, non-zero), it would work correctly, which meant ignoring the data maps and doing what was needed to have the data be entered correctly.

      I ended up getting moved to another customer (due to the limited resources *we* had, not because of my creativity), so I don't know if the remaining folks on the project removed it after I left. When I added it, I explained to them precisely why I'd added it, and since they'd had similar experiences with what we were given to work with, were behind me 100%.

      This wasn't even the *only* part of the project which was FUBARed, but it was unfortunately what I spent many a 15+ hour day dealing with, so I was rather familiar with it. Had I access to the server that *read* the data and used it, I probably would have just gone in and redesigned everything "for free", just to avoid having to deal with such a horrible layout.

      This is also the client where, after a few months of an irksomely out of sync clock (off by 12 hours...made figuring out when something happened a bit of a PITA), I finally went in and set the damned clock to the proper time. Not surprisingly, the same folks who made that wonderful novel for us were the ones admining the dev server we were working on. AFAIK, no one ever noticed that the time suddenly became "correct" either.
      [ Parent ]
    • Re:Variable Names by Iffy Bonzoolie (Score:1) Monday May 20 2002, @04:35AM
    • Re:Variable Names (Score:5, Interesting)

      by Grab (126025) on Monday May 20 2002, @05:10AM (#3549090) Homepage
      Sometimes, from other ppl. If I see it, it goes right back in review, and I won't pass the review until the fuckwit responsible has removed them. If you're writing code for yourself, then fine, please yourself. If you're writing code that anyone else will see, *especially* the customer, then hell no.

      Thing is, there's two essential things that a reviewer/maintainer has to understand about a program: what it does; and why it does it. It should be possible to work out the first one of these just from the code, so long as the variables and functions are named sensibly. The second can be worked out from code with some effort, or the coder can add comments to explain why they're doing things that way and make it easier for maintainers.

      But if someone has deliberately given all the variables names which don't reflect what they do, then it's utterly impossible to work out what the code is doing, and it's therefore also impossible to work out why it's doing it. So the code is unmaintainable - it isn't possible for anyone else to pick it up and work out what it does, except with massive work. If in 6 months time your company says "oh, we've got this code we can use with slight modifications, let's quote 1 month to do this contract" and then they find out you've made the code utterly obscure, then they'll crash and burn. And if that happens, the company *will* fire (or at least formally discipline) the person who wrote the original code, bcos they've been grossly negligence in doing their job. And you can kiss goodbye to any reference from them, so you'll be SOL in finding your next job.

      Grab.
      [ Parent ]
    • Re:Variable Names by ColdGrits (Score:1) Monday May 20 2002, @05:11AM
    • Re:Variable Names by Dynedain (Score:2) Monday May 20 2002, @05:28AM
    • Re:Variable Names by Squashee (Score:2) Monday May 20 2002, @05:56AM
    • Re:Variable Names by Aqua OS X (Score:2) Monday May 20 2002, @06:19AM
    • Re:Variable Names by Anonymous Coward (Score:2) Monday May 20 2002, @08:10AM
    • Constructive comment on symbol names by mpsmps (Score:1) Monday May 20 2002, @08:34AM
    • Re:Variable Names by SurfTheWorld (Score:1) Monday May 20 2002, @09:20AM
    • Re:Variable Names -consistency by DrCode (Score:2) Monday May 20 2002, @11:51AM
    • Re:Variable Names by sister_snape (Score:1) Monday May 20 2002, @06:43PM
    • Re:Variable Names by McPierce (Score:1) Tuesday May 21 2002, @06:53AM
    • Re:Variable Names by mustangsal66 (Score:2) Tuesday May 21 2002, @09:48PM
    • Re:Variable Names by peddrenth (Score:2) Monday May 20 2002, @05:37AM
    • people like you give coders a bad name by CrudPuppy (Score:1) Monday May 20 2002, @08:59AM
    • Re:Variable Names by Paranoid (Score:2) Monday May 20 2002, @10:11AM
    • Re:Variable Names by PepsiProgrammer (Score:2) Monday May 20 2002, @09:55PM
    • 4 replies beneath your current threshold.
  • Code Complete (Score:5, Informative)

    by kimba (12893) on Monday May 20 2002, @03:21AM (#3548808)
    I can absolutely recommend a book called Code Complete [amazon.com]. Yes, it is published by Microsoft, but it is an invaluable language-agnostic guide to writing software that includes heavy doses of common sense regarding commenting, coding styles etc.
  • Make the variable names mean something! by dweezle (Score:2) Monday May 20 2002, @03:23AM
  • Describe before you apply (Score:3, Funny)

    by inflex (123318) on Monday May 20 2002, @03:23AM (#3548816)
    I like to see comments where the function of the next code block is well described in a continuous comment block. Additionally, any further specific comments can be placed at the end, or on top of the lines in question. It's simple enough, and permits comment/documenting-scrapers to produce some potentially useful documentation.


    ie,
    // Foo():infinite loop
    // We attempt to complete an infinite loop
    // here as quickly as possible, in order to
    // remain true to Linus's statements of
    // being able to do them faster with linux.
    while (1) {
    ... // Oooh, this is a fancy line, watch out for it doing nothing.
    }

    • Re:Describe before you apply by ranulf (Score:2) Monday May 20 2002, @03:43AM
    • Multiple passes to your code (Score:4, Insightful)

      by fractaltiger (110681) on Monday May 20 2002, @03:44AM (#3548889) Journal
      are the best way to comment it all.

      One day you're commenting on what variables do, the next you try to explain functions, etc.

      I just switched to Java from C++ and neatness is the most important thing I've acquired, not in code per se, but in variable naming. I've gotten used to doingThisWithVariableNames and DoingThisWithClassNames, while keeping THE_CONSTANTS capitalized. Ok, this isn't comments? But you'll be surprised at how much better it is to browse a new language like Java and see the norms of style in it, because old languages use too many confusing double_StandardslikeWritingThis_way.

      Comments go at the top of a page, with the coder's name and date, as well as a small bug report and if you can, a brief function list for those without a visual IDE like JBuilder. You then put a like with PRE: and POST conditions in your code and try to keep one liner comments to a min.

      I learned to comment the end of if structures and function blocks to make the code easier to follow... just add " } //end if" or something.

      Comments should be a paragraph long so that they make some sense. And comments, since they look different from the code sections, should be embelished with ===============, stars, and some
      nice spacing and vertical bars.

      Good comments to me mean good-looking comments, even if they don't have that much substance. Just my 2 cents. They're better than no comments at all.
      [ Parent ]
  • Microsoft Press by ObviousGuy (Score:2) Monday May 20 2002, @03:24AM
  • Per project by mnordstr (Score:2) Monday May 20 2002, @03:25AM
    • Re:Per project by looseBits (Score:1) Monday May 20 2002, @10:24AM
    • Re:Per project by Euphonious Coward (Score:2) Monday May 20 2002, @07:48PM
    • 1 reply beneath your current threshold.
  • Timeless Prof D.Knuth says it best... by gmarceau (Score:2) Monday May 20 2002, @03:26AM
  • Good Commented Code by guinan (Score:1) Monday May 20 2002, @03:26AM
  • Just tell me what a section of code is for. by foniksonik (Score:2) Monday May 20 2002, @03:26AM
  • Good Comments (Score:4, Insightful)

    by jamieo (22197) on Monday May 20 2002, @03:26AM (#3548828) Homepage
    Good code comments should describe the intention of the code. Write them *before* you write the code in a function/method to describe it's purpose. This will make you think exactly what you want it to do, and will allow for others to find/fix bugs easier when the implementation doesn't meet the intention.

    I then write inline comments in the code describing it's flow. It's only then do I actually write the code.

    Comments at file/class level should describe what it does and is used for. It should also describe how it fits in with the big picture of it's packages and the classes around it - give a reader some architectual scope to what they're looking at.

    Get into a habit, even for trivial functions/methods and you'll soon not realized you're doing it.

    Some people say code shouldn't need commenting, and the code itself should be enough. In a perfect world of no bugs and only populated by wizard programmers, this is fine, but not in the world I live in. You write some code and someone else (maybe yourself) will have to debug it at some point - maybe 3-4 years down the line. Even with a "neat" language like Java, working out how things work is much more time consuming without comments.
    • Re:Good Comments by reinterpret_cast (Score:1) Monday May 20 2002, @03:49AM
    • Re:Good Comments by terminal.dk (Score:1) Monday May 20 2002, @04:39AM
    • Re:Good Comments (Score:4, Insightful)

      by Cederic (9623) on Monday May 20 2002, @07:05AM (#3549361)

      Congrats, you've just described a maintenance nightmare.

      Every time someone has to change some code, you've just forced them to double their workload, and change some comments too.

      If they forget, or don't have time, or are lazy, or don't notice the comment (it's easy to blank them out) then the comment doesn't get updated.

      Now you have a comment that is wrong. And that is so so so much worse than having no comment at all.

      Comment sparsely. Do not sprinkle your code with comments. Especially do not use comments like

      // increment loop counter
      loopCounter++;

      That is adding zero value.

      Inline comments are a major headache - they're painful to write, painful to maintain, and dangerous if they aren't maintained.

      ~Cederic
      [ Parent ]
      • Re:Good Comments (Score:5, Insightful)

        by MadAndy (122592) on Monday May 20 2002, @07:33AM (#3549495)
        Changes have to be done twice? That's right, when they change the code, they must change the comment.

        I'll repeat that: they MUST change the comment. And it must make complete sense when they're done or they'll be out of a job!

        Why is this important? When you change the comment, you must think about the comment. You must think about the change you've done and how it fits in with the rest of the code, and what the rest of the code is trying to do. If a comment isn't up to date or doesn't make sense, that's a bug in the code, as bad as any other, and it needs to be fixed.

        It's not difficult to spot when the comments don't line up, so they're fairly easy to fix. While you're there fixing the comments you need to check the code, 'cos whoever the idiot was that wrote it, they obviously haven't checked it properly. Go and hit them with a Very Big Stick.

        Certainly you shouldn't whine about the extra typing. A little extra typing shouldn't hurt - and you should be able to type faster than you can think, so it shouldn't really slow you down. If it does, go take a typing class.

        And if your lame excuse is that you're in too much of a hurry to maintain comments, just make sure you're not in too much of a hurry to deal with the bug reports that come back because you haven't checked your code properly.

        [ Parent ]
      • Re:Good Comments (Score:4, Insightful)

        by Simon Brooke (45012) <simon@jasmine.org.uk> on Monday May 20 2002, @07:53AM (#3549605) Homepage Journal
        Every time someone has to change some code, you've just forced them to double their workload, and change some comments too... Inline comments are a major headache - they're painful to write, painful to maintain, and dangerous if they aren't maintained.

        ... and absolutely essential to the poor bastard who comes after you - without them he has zero chance. I spent some hours on the phone a couple of days ago talking some poor lad in the states through the trickier bits of one of my open source packages. Fortunately it is inline-commented, so I at least knew what I had been intending to do.

        I agree with everything you say about the nuisance of maintaining comments, and I agree with everything you say about the problems that happen when you fail adequately to maintain comments. It's a chore; but it's a vital chore. It's got to be done.

        [ Parent ]
      • Re:Good Comments by ebbe11 (Score:1) Monday May 20 2002, @10:09AM
      • It's sophomores like you... (Score:5, Informative)

        by Pollux (102520) <splien&gauss,cord,edu> on Monday May 20 2002, @10:19AM (#3550805) Journal
        ...who make reviewers like me stare at computer screens for endless hours trying to figure out how the hell your computer code is supposed to work.

        Comment sparsely. Do not sprinkle your code with comments. Especially do not use comments like

        Yea, I can already picture your programming style. You'd make a 200-line function with the only comment being " // Creates hash table ". Question: Where does that leave me? When I find out that there's some problem in the hash algorithm, I have to dig through 200 lines of code to find some freakin' bug that is described only by "Creates hash table." Your example of why comments don't need to be made is a poor one:

        // increment loop counter
        loopCounter++;


        That is adding zero value.

        Yes, because it's one line of code, and the code is described through the variable. But when sifting through lines of code, you often find beautiful works like iHateMyJob++; or fuckMyBoss--; to name a few. And needless to say, they're uncommented in the code. Until computer code can be written bug free in complete English sentences (aka Never), the rest of your team of workers needs to understand what your code does.

        Personally, I make sure every function says what goes into it, what comes out of it, and what setup (variables, etc.) need to be made for it to be called. I do not comment every single line of code, but I do make sure that every line is accounted for by descriptive sentences, explaining the task that I wish to accomplish as well as what variables / registers / actions I take to accomplish the task.

        Every time someone has to change some code, you've just forced them to double their workload, and change some comments too.

        Okay, this just pisses me off. You didn't mean what you said. Here's what you meant to say:

        Every time I have to change some code, you've just forced me to double my workload, and change some comments too.

        I can assure you, from a reviewer's point of view, comments SAVE my time from trying to understand what each piece of code is trying to accomplish. Commented code may make you work extra time to detail the lines of code (I do admit, some programmers are quite tallented at keeping track of every single line of code in their head as they work on it on the computer), but it saves tremendous amounts of time once that chunk of code needs to be integrated with other chunks of code into the final product.
        [ Parent ]
      • Re:Good Comments by jamieo (Score:3) Monday May 20 2002, @10:29AM
      • Re:Good Comments by ProlificSage (Score:1) Monday May 20 2002, @10:29AM
      • so YOU'RE the guy... by Twister002 (Score:1) Monday May 20 2002, @11:32AM
      • Re:Good Comments by ClarkEvans (Score:3) Monday May 20 2002, @11:48AM
      • Re:Good Comments by ebyrob (Score:2) Monday May 20 2002, @05:30PM
      • Better practice-- inline comments tell why not how by einhverfr (Score:3) Monday May 20 2002, @06:27PM
      • 1 reply beneath your current threshold.
    • Re:Good Comments by locutus2k (Score:1) Monday May 20 2002, @08:42AM
    • Re:Good Comments by G-funk (Score:2) Monday May 20 2002, @08:53AM
    • Re:Good Comments by hey! (Score:2) Tuesday May 21 2002, @01:45PM
    • 4 replies beneath your current threshold.
  • my work by drDugan (Score:2) Monday May 20 2002, @03:27AM
  • Use plenty of expletives (Score:5, Funny)

    by oingoboingo (179159) on Monday May 20 2002, @03:27AM (#3548831)
    Well commented code should definitely contain a liberal smattering of four-letter expletives, eg:


    // no fucking idea how this works
    obj.doMagic();


    or...


    //bet those fucking lazy cunts in the QA team don't pick this up
    fileSystem.delete();


    When your code is released as open source and becomes famous, people can amuse themselves by searching through the source code to find all the hidden expletives, sort of like easter eggs. If you work for a commercial organisation, you can sit back and enjoy the panic as the QA and release teams sweat it out trying to track down every last filthy utterance before shipping to a fucker...errr..customer.
  • Doxygen, etc (Score:5, Informative)

    by Stary (151493) <stary@novasphere.net> on Monday May 20 2002, @03:29AM (#3548836) Homepage Journal
    Tools like javadoc, or maybe better in your case doxygen [stack.nl] can really help when it comes to commenting code... the idea is pretty much that you place a documentation comment before each function, or class, and so on, which usually makes the entire thing much easier. Having done that, I've found that only a few more non-obvious parts have to be commented within the actual functions.
  • How to write unmaintainable code by xmda (Score:1) Monday May 20 2002, @03:29AM
  • Rule of thumb by Overcoat (Score:1) Monday May 20 2002, @03:29AM
  • Simple rule of thumb by nagora (Score:1) Monday May 20 2002, @03:29AM
    • Re:Simple rule of thumb by FatAlb3rt (Score:1) Monday May 20 2002, @09:01AM
    • Re:Simple rule of thumb (Score:4, Interesting)

      by nagora (177841) on Monday May 20 2002, @04:18AM (#3548989)
      Write code that is easy to understand and comment about wierd / unusual sections

      Nice idea; never works in practice. The reason is that what you think is easy to understand is not always what other people think is easy to understand.

      The code you are writing now might have to be modified in the future by someone just out of university which means, generally, someone with very little experience. Your red-black binary tree might be "easy to understand" for you and a novelty to them.

      Also, mature highly-factored, optimised code that has been improved over several years can be very hard to follow even when the original code was quite straight-forward (but perhaps too slow).

      Finally, as a philosophical point, source code is supposed to be terse in comparison to natural language so it should take longer to describe the code in your own language than in the programming language.

      TWW

      [ Parent ]
    • Re:Simple rule of thumb by nagora (Score:2) Monday May 20 2002, @04:32AM
    • 2 replies beneath your current threshold.
  • Overload whitespace to something meaningful! by Lt.Hawkins (Score:1) Monday May 20 2002, @03:30AM
  • a set of standards is the key by potcrackpot (Score:1) Monday May 20 2002, @03:30AM
  • K&P's "Practice of programming" by Anonymous Coward (Score:1) Monday May 20 2002, @03:31AM
  • Coding Standards by benjymous (Score:1) Monday May 20 2002, @03:31AM
  • commenting code by caca_phony (Score:1) Monday May 20 2002, @03:33AM
  • CRC please... by shic (Score:1) Monday May 20 2002, @03:33AM
  • Different parts of the brain by heretic108 (Score:2) Monday May 20 2002, @03:34AM
  • It's been a long time but.. (Score:5, Interesting)

    by NewtonsLaw (409638) on Monday May 20 2002, @03:34AM (#3548857)
    It's been quite a while since I wrote any significant amount of code but after spending far too many years cutting code too early in the development process I eventually woke up to the fact that coding is the *last* thing you do (apart from testing and debugging that is).

    First-up you need a good spec -- and the spec should include the user-interface details to the extent that you could actually write the user-manual from that spec.

    Indeed -- if you can't write the user-manual from the spec then the spec is incomplete.

    From the spec the programmer should develop the structure of the code in another document.

    That structure document is repeatedly refined in a top-down process until you (eventually) reach a point where you're actually cutting code.

    I was always surprised just how much easier it was when the code was written as the lowest level of the structure documentation.

    Not only could you comment out the program structure document so that the compiler would ignore it -- but you ended up with absolutely accurate and comprehensive documentation built into that source.

    Project managers love this technique (and when I was in a project management role I demanded it of my team) -- it ensures that technical and end-user documentation are no longer the bits that get left until last and thus are either very shoddily thrown together or, if the project goes really over-budget, not produced at all.

    Of course, as we all know, there's a huge amount of temptation to just leap into coding at the earliest possible stage and leave the documentation until later -- because some stupid managers use number of code-lines completed as a metric of project performance -- duh!

    If you're smart and use good tools you can selectively collapse and expand the in-source documentation so that when you're trying to get familiar with a module that someone else has written, you can descend down the structure tree one level at a time without the meaning being diluted by stuff that is at a lower level.

    Unlike the days of interpreted BASIC, there's very little overhead involved in integrating documentation and code these days -- so there's no excuse not to do it.

    If required, the documentation can be automatically extracted from the source -- but by keeping the master copy in the code it becomes easier to ensure synchronization as changes and updates are made during the lifecycle of the project.
  • UML and RUP by mikolajl (Score:1) Monday May 20 2002, @03:36AM
    • 1 reply beneath your current threshold.
  • Good coding method by dybdahl (Score:1) Monday May 20 2002, @03:38AM
    • 1 reply beneath your current threshold.
  • Document the function's contract (Score:5, Interesting)

    by IvyMike (178408) on Monday May 20 2002, @03:41AM (#3548878)

    Take a look at this function, and tell me if there's a bug:

    void foo(void) {
    int* x = 0;
    int y = *x;
    }

    Easy, the bug's the SEGV, right? Take a look at the same function, this time with comments:

    // Function: cause_segv
    // Description: Causes a SEGV for testing purposes
    void cause_segv(void) {
    int* x = 0;
    int y = *x;
    }

    The point? A bug is unwanted behaviorm, but that only makes sense if you've defined what the correct behavior is. My example is trivial, but often this is a real concern. Function "bar(int,int)" returns null whenever one of the arguments is negative--is that a bug or a feature? Your function has a goal in life, a contractual obligation to do something; make sure it's clear what that something is.

    Note that if you choose good function and good variable names, a simple one or two line comment at the beginning is usually sufficient to document whe function's intended behavior.

    I also find that an "assert()" or two on the arguments at the top of the function makes it clear what values the function accepts, and which one the function doesn't handle. It's an easy way to document the contractual obligations of the function.

    Stuff not to put in comments is stuff that's easily devised from the code. Check this out:

    // Function: square
    // Inputs: int x
    // Outputs: int
    // Used by: pythagorean(int,int)
    // Description: returns x squared
    int square(int x) { return x*x; }

    Did the "Inputs" or "Outputs" add any value? That information appears again, two lines below in the function definition, and it's guaranteed to be correct there (unlike the comment which will be out-of-date and wrong when we change "square" to work on longs). The "Used by" might have added some value, if it was correct, but as it turns out it's out of date, and 15 other functions now use "square". Any information better derived looking at the code should be left off. Any information which can be better found using "grep" or "find in files" should be left off. Any information that will probably be out of date at some point should be left off. Heck, in this situation even the description is probably extra verbiage, since it doesn't really help anyone. (I'd probably put it in out of habit anyway, though...so sue me:)

    • type* var is evil by inflex (Score:1) Monday May 20 2002, @03:47AM
      • Re:type* var is evil by ObviousGuy (Score:1) Monday May 20 2002, @03:51AM
      • Re:type* var is evil by silvaran (Score:1) Monday May 20 2002, @03:59AM
      • Re:type* var is evil by Twylite (Score:2) Monday May 20 2002, @04:03AM
      • Re:type* var is evil (Score:5, Insightful)

        by emag (4640) <slashdot&gurski,org> on Monday May 20 2002, @04:14AM (#3548979) Homepage
        Oh, you've really touched on a sore spot. At a company I worked for once, there was a group of managers and developers who were working on coding standards for the entire division. Somehow, since *my* manager knew I was a fairly proficient coder, and wanted to make sure our group had input, I ended up on the panel. I remember telling a manager for another project point blank that he was an idiot for insisting that:

        char* foo, bar;

        was good coding practice, while

        char *foo, bar;

        wasn't, because the code was declaring two pointers, and so the * should be with the type and not the variable name.

        Even pulling out K&R, and writing sample code showing the sizeof(foo); vs the sizeof(bar); wouldn't convince him that he was wrong.

        Unfortunately, I don't think it was ever "officially" settled. Nor were several of the other corrections that I immediately made to his "proposed" coding standards document he handed out at the first meeting.

        Thankfully, my manager at the time listened to me (and also, helpfully, knew C and C++), so when we got the coding standards, they were filed with the rest of the useless paperwork we got, and we kept on writing things properly, including:
        • comment blocks before each function describing usage, parameters, expected range of return values, and error conditions
        • comments describing thee amount and type of testing done to verify things worked
        • comments about who had done what with what code and when
        • comments preceeding anything non-obvious about the code itself


        Three guesses as to which project was ahead of schedule. (Of course, not entirely fair, since we also didn't force code generation via Rational Rose. We instead reverse-engineered all of our final UML from the code we'd written and tested, and knew worked the way it was supposed to...)
        [ Parent ]
      • Re:type* var is evil by Tony-A (Score:2) Monday May 20 2002, @04:31AM
        • 1 reply beneath your current threshold.
      • Re:type* var is evil by IvyMike (Score:2) Monday May 20 2002, @11:48AM
    • Braces by Kwil (Score:1) Monday May 20 2002, @03:56AM
      • Re:Braces by ObviousGuy (Score:1) Monday May 20 2002, @04:04AM
        • Re:Braces by thogard (Score:2) Monday May 20 2002, @06:17AM
          • Re:Braces by Anomie-ous Cow-ard (Score:1) Monday May 20 2002, @06:57PM
          • Re:Braces by himi (Score:2) Monday May 20 2002, @08:57AM
          • Re:Braces by thogard (Score:1) Monday May 20 2002, @09:44AM
          • 1 reply beneath your current threshold.
      • Re:Braces by Ed Avis (Score:2) Monday May 20 2002, @04:42AM
      • Re:Braces by IvyMike (Score:2) Monday May 20 2002, @12:05PM
        • Re:Braces by Finagle's Friend (Score:1) Tuesday May 21 2002, @02:54AM
          • Re:Braces by IvyMike (Score:1) Tuesday May 21 2002, @10:27AM
    • Re:Document the function's contract by awol (Score:1) Monday May 20 2002, @04:07AM
    • Re:Document the function's contract by natmsincome.com (Score:1) Monday May 20 2002, @07:46AM
    • Re:Document the function's contract by Darth_Burrito (Score:2) Monday May 20 2002, @11:20AM
    • Re:Document the function's contract by JBHemlock (Score:1) Monday May 20 2002, @12:11PM
  • Folding helps by AlecC (Score:1) Monday May 20 2002, @03:41AM
  • Examples.. (Score:5, Funny)

    by popeyethesailor (325796) on Monday May 20 2002, @03:42AM (#3548881)
    # all of these will also get moved elsewhere

    # this is the worst damned warning ever, so SHUT UP ALREADY!

    # Keep your friends close but your enemies closer.
    # Or ignore them, we don't care.

    # You know, we do assume comments are linear -Brian
    Refer here [slashcode.com] for further details:)
  • from /usr/src/linux/Documentation/CodingStyle by mav[LAG] (Score:2) Monday May 20 2002, @03:42AM
  • PDL it is good no? (Score:3, Interesting)

    by ZanshinWedge (193324) on Monday May 20 2002, @03:44AM (#3548890)
    Personally, I like documenting backwards. Start with the requirements, work to the architecture, then get into writing PDL (Program Design Language). Essentially, you write out as detailed instructions on what the routine does as you can, without getting to the nitty gritty. It describes the intent of the code, not the code itself. It morphs into excellent comments when you expand it out into full code, and it also has the nice little advantage that it's at a high enough level that it's applicable to multiple languages (if you should desire to switch).
  • Offtopc(-1) by jgp (Score:1) Monday May 20 2002, @03:44AM
  • Literate programming by awol (Score:1) Monday May 20 2002, @03:45AM
  • style(9) by RinkSpringer (Score:1) Monday May 20 2002, @03:45AM
    • 1 reply beneath your current threshold.
  • Linux and other things. (Score:4, Insightful)

    by jon_c (100593) on Monday May 20 2002, @03:48AM (#3548906) Homepage
    Personally I think the linux kernel is very well documented, at least the scheduling part, which is what I've looked at. Linus has a style of inserting huge comment blocks that explain exactly what's going on, then he'll have a page of code that does it, with little or no comments.

    A style suggested in Code Complete (I forget what they call it) is to write a method completely in pseudo code, make sure it's correct, then insert the actual programming code under each line of pseudo code. This technique, while clever I find leads to many useless comments like "loop through the employee records" and "increment the counter".

    A good test to see if the comments are working is through a code review, people will very often not know what's going on, or point out confusing comments or code that needs a better explanation. Code Reviews really improves your idea of what good comments are and teaches you what works and what doesn't.
  • Coding Style by calzplace (Score:1) Monday May 20 2002, @03:54AM
  • Inline Documetation and Automated Tools by twoshortplanks (Score:1) Monday May 20 2002, @03:54AM
  • Code Commenting? by mthed (Score:1) Monday May 20 2002, @03:54AM
  • Good commenting (Score:3, Insightful)

    by RockyJSquirel (412960) on Monday May 20 2002, @03:55AM (#3548925)
    I wish I had time to go into more detail but I recommend:

    1. Every class should have a clearly defined public interface and documentation of:
    a) what the class is for and (if appropriate) why it was designed the way it was
    b) how it works
    c) how to use it
    d) how to extend it (if there's any reason to do so)
    e) it's lifetime / memory usage(if appropriate)
    f) if it's tightly connected to any other classes or functions, that should be documented
    g) how to make classes derived from it (if appropriate)

    2. Every function should have a comment that says:
    a) what it does
    b) why (if there's any question)
    c) what side effects it has (if any)
    d) what side effects it depends on (if any)
    e) if the functions is tightly bound to any parts of the program (it's not a context free sort of routine) then you should list where it's called from.
    f) examples of how its used (if appropriate)
    g) This one is important: describe the algorithm. It's important to keep this sort of comment up to date.

    I'm not so enthusiastic about comments on individual lines of code. They seem less necessary to me than the other sorts of comments, especially if everything is well named.

    I've been trying to get people at my latest company interested in code documentation, but I seem to have lost that battle. It's a shame. The only way to develop around here is to read every damn line of code, and that's unbelievably wasteful.

    Rocky J. Squirrel
  • Read this book! by Joystickit (Score:1) Monday May 20 2002, @03:56AM
  • Don't write complex functions! by alek202 (Score:1) Monday May 20 2002, @03:58AM
  • Screw comments by firegate (Score:1) Monday May 20 2002, @03:58AM
  • Why not what by joss (Score:2) Monday May 20 2002, @03:59AM
  • code comments by VonKruel (Score:2) Monday May 20 2002, @04:00AM
  • Tools matter by wray (Score:1) Monday May 20 2002, @04:04AM
  • Jutil.org documentation by MarkoNo5 (Score:1) Monday May 20 2002, @04:05AM
  • CWEB by D.E.Knuth by hobbes75 (Score:1) Monday May 20 2002, @04:07AM
  • Pseudo code and formatting by silentbozo (Score:2) Monday May 20 2002, @04:11AM
  • Proper Commenting of Code by joe52 (Score:2) Monday May 20 2002, @04:11AM
  • Have a standard by Paul Johnson (Score:2) Monday May 20 2002, @04:12AM
  • Comment the data structures. by davec (Score:1) Monday May 20 2002, @04:13AM
  • Location, location, location by ralphbecket (Score:2) Monday May 20 2002, @04:13AM
  • Hungarian Notation (Ugh!) by caveman (Score:2) Monday May 20 2002, @04:17AM
  • Check out how not to do it. by chrestomanci (Score:2) Monday May 20 2002, @04:17AM
  • more isn't necessarily better by g4dget (Score:1) Monday May 20 2002, @04:17AM
  • Comments Considered Harmful (Score:3, Interesting)

    by Bazzargh (39195) on Monday May 20 2002, @04:18AM (#3548992)
    This has come up before - in Martin Fowler's book, "Refactoring", he makes the controversial claim that sometimes comments are indicative of a need to change the code.

    Consider the different types of comment:
    - boilerplate comment at the top of a file: helps noone but lawyers.
    - change history comment: better use your source control tool to maintain this.
    - comment before a class: does this mean the class is badly named, or too complex?
    - comment before a method: ditto.
    - comment inside a method: could be a smaller method screaming to get out.
    Also heavily commented code is quite commonly just explaining away stupid code tricks.

    Nobody's suggesting that all comments are bad, just that a lot of the time adding comments is a poor substitute for fixing whats wrong with the code. Of course sometimes its the language thats the problem :)

    -Baz
  • Design by Contract by MosesJones (Score:2) Monday May 20 2002, @04:24AM
  • Code for humans not machines by saphena (Score:1) Monday May 20 2002, @04:28AM
  • comment the data structures too by digital labourer (Score:2) Monday May 20 2002, @04:31AM
    • Brooks! by mikeee (Score:2) Monday May 20 2002, @09:53AM
  • Document abnormal behaviour by tve (Score:2) Monday May 20 2002, @04:32AM
  • it is well commented code... by sirius_bbr (Score:1) Monday May 20 2002, @04:34AM
  • Good Naming and Factoring are More Important by Anonymous Coward (Score:1) Monday May 20 2002, @04:38AM
  • Work from the top down by Daetrin (Score:2) Monday May 20 2002, @04:39AM
  • My favorite comments (Score:5, Funny)

    by bentini (161979) on Monday May 20 2002, @04:42AM (#3549037)
    I personally despise comments such as:

    i++; //increments the variable i

    I think that they are unclear and do not properly explain the situation. Remember, you're writing so people can UNDERSTAND the code, not so that you can impress them with how smart you are. Instead, strive for a comment like this:

    i++; /*changes the value stored in the space referred to by i to be the sum of the old value stored in the space referred to by i and the constant 1. Note: In C, this may cause what is known as a "silent overflow" if the value is too large, and go so far as to make a large positive value into a larger negative one. Oh my!

    This way, people who read your code not only understand your program, but all programs. I really think that each function you write should repeat a semester's worth of computer science theory and programming practice, so that anyone who reads your code will learn from it. Remember, not everyone knows idioms, and why should they? And since we all write open source on slashdot, many novices are going to have their introduction to any computing environment by looking at the code you write at any point.

    Your most humble and obedient servant,
    Dan

  • blah.c by Ketnar (Score:1) Monday May 20 2002, @04:43AM
  • Some examples of bad comments by Dr. Tom (Score:2) Monday May 20 2002, @04:44AM
    • 1 reply beneath your current threshold.
  • Two basic rules by edhall (Score:2) Monday May 20 2002, @04:48AM
  • External API by Snake (Score:1) Monday May 20 2002, @04:49AM
  • Style. by NullStream (Score:1) Monday May 20 2002, @04:54AM
    • 1 reply beneath your current threshold.
  • Formatting by Dr. Tom (Score:2) Monday May 20 2002, @04:56AM
  • Commenting "null" code by Zocalo (Score:2) Monday May 20 2002, @04:56AM
  • You are not expected to understand this. by dc.wander (Score:1) Monday May 20 2002, @04:57AM
  • Code Commenting by j_kenpo (Score:1) Monday May 20 2002, @05:02AM
  • Comments are only a part of the answer by PinglePongle (Score:2) Monday May 20 2002, @05:05AM
  • Tracing by slim (Score:2) Monday May 20 2002, @05:08AM
  • Commenting Code by lemkebeth (Score:1) Monday May 20 2002, @05:11AM
  • WHY not WHAT by mikehunt (Score:2) Monday May 20 2002, @05:11AM
  • The Code Dictator by Knacklappen (Score:1) Monday May 20 2002, @05:23AM
  • Things to bear in mind (Score:5, Insightful)

    by Rogerborg (306625) on Monday May 20 2002, @05:33AM (#3549127) Homepage
    • All modern compilers that I know of can handle symbol names of at least 256 characters, not the old 31 character limit.
    • The most widely understood naming convention is the English language.
    • If you feel that you have to comment the purpose of a method, function or variable when you declare/define it, why isn't it necessary to comment every use of it as well?
    • The time spend typing or reading characters of code is insignificant compared to the time spent comprehending it.
    • Whenever you write code that requires any interpretation at all, you cost yourself developer time, and that's a precious resource.
    • If you comment something that the language supports, you're not using the language.
    • People who slate you for using over-verbose naming are really saying "You shouldn't need long names to understand my code." That's a solipsistic ego trip, as the target audience isn't or your peers or anyone in a code review or with white box knowledge of the code or system. It's the poor contractor shmuck five, ten or fifteen years down the line who has to come to your code stone cold on to fix a critical bug with a deadline breathing down his neck and a hankering to get the hell out of the office and have some semblance of a life. Write for the benefit of that guy, because one day you'll probably become him.
    • Every time you write a comment, you introduce a potential headache for the maintainers. Ask yourself when the last time you updated a comment in production was, even when it contradicted the code.

    Here's the rules I use:

    • A function/method name is too long when it doesn't fit on a typical screen. 80 characters is about my limit.
    • If I find myself thinking that I'd better comment the purpose of a variable, I incorporate the comment in the variable name. As a side effect, that also tends to give a good feel for how important a variable is.
    • Yes, we all know that "i" is a counter, but what is it counting? It costs me perhaps five seconds to use a variable that describes what is being counted. Then it costs a reader an extra tenth of a second to read it, but that saves a quarter of a second to translate to what it actually means. Let people read your code, don't keep making them stutter and recap.
    • Describing the function and purpose of "input" and "output" parameters in a function description comment is a hell of a long winded way of typing "const WhatTheParameterIsActuallyUsedFor". You only have to type it once; that's what copy and paste is for. Don't comment expected values, assert(them).
    • Completely self commenting code is an unrealistic ideal. But get as close to that ideal as possible, and don't be afraid to change comments when you change the code during maintenance. If you're sure what the code deos, you should have no problems doing that. If you're not sure what the code does, then find out.
  • My take on it by SashaM (Score:1) Monday May 20 2002, @05:37AM
  • Too many comments? by erpbridge (Score:2) Monday May 20 2002, @05:46AM
  • comments are extra by dollargonzo (Score:1) Monday May 20 2002, @05:51AM
  • My preferences by Piquan (Score:2) Monday May 20 2002, @05:55AM
  • Code that is hard to write... by SilverThorn (Score:1) Monday May 20 2002, @05:57AM
  • Bad question by MagPulse (Score:1) Monday May 20 2002, @06:00AM
  • Literate programming... by oren (Score:1) Monday May 20 2002, @06:02AM
  • my code will get me killed by TheCyko1 (Score:1) Monday May 20 2002, @06:02AM
  • Important to maintain comments by coreman (Score:2) Monday May 20 2002, @06:05AM
  • ccdoc by CoolGopher (Score:1) Monday May 20 2002, @06:14AM
  • Over commented example by ch-chuck (Score:2) Monday May 20 2002, @06:21AM
  • Describe your design decisions and thought process by mfarah (Score:2) Monday May 20 2002, @06:34AM
  • Favor Code Clarity Over Comments (Score:5, Insightful)

    by Bob9113 (14996) on Monday May 20 2002, @06:36AM (#3549258) Homepage
    In any situation where I see the need for code commentary, I try first to find a way to make the code clearer. If the source code is sufficiently clear, comments are unnecessary. This also avoids the risk that the comments will diverge from the code - making claims that were once true, but no longer reflect the code's actual logic.

    This is poorly commented code (despite the fact that the comment is clear and accurate):

    aClassName = aTask.getUiInitializerClassName();
    // empty or null uiInitializerClassName means this task is not
    // defined for use in this interface. Skip it.
    if( aClassName != null && ! aClassName.equals( "" ) ) {
    ... do something ...
    }


    This is well commented code (despite the fact that there are no comments at all):

    initializerName = aTask.getUiInitializerClassName();
    boolean isNotNull = initializerName != null;
    boolean isNotEmpty = ! initializerName.equals( "" );
    boolean definedForThisUi = isNotNull && isNotEmpty;
    if( definedForThisUi ) {
    ... do something ...
    }

    Of course, this doesn't work in all situations, but I find that I can improve the clarity and accuracy of seventy to eighty percent of my commentary this way.
  • Comments as API spec / programming guide. by vil (Score:1) Monday May 20 2002, @06:39AM
  • comments by small_box_of_stuff (Score:1) Monday May 20 2002, @06:40AM
    • Re:comments by TheShadow (Score:1) Monday May 20 2002, @06:47AM
  • Commented line or commented block and nameing by Flu (Score:1) Monday May 20 2002, @06:43AM
  • University CS Standards. by CrazyDuke (Score:1) Monday May 20 2002, @06:47AM
  • Worst comment I ever saw by dannyspanner (Score:1) Monday May 20 2002, @06:47AM
  • Document the intention by BbMaj7 (Score:1) Monday May 20 2002, @06:53AM
  • Too many lameness characters by CrazyJim0 (Score:1) Monday May 20 2002, @06:55AM
  • Be suspicious of comments.... by borgboy (Score:1) Monday May 20 2002, @07:05AM
  • Go to college by Ricky Glaze (Score:1) Monday May 20 2002, @07:06AM
  • Why software patents are bad... by wfberg (Score:2) Monday May 20 2002, @07:07AM
  • Documentation is not just comments in the code by shoppa (Score:2) Monday May 20 2002, @07:09AM
  • The best comments are the code itself by chrysalis (Score:2) Monday May 20 2002, @07:12AM
  • Remember, comments don't have to make sense by lightspawn (Score:2) Monday May 20 2002, @07:16AM
  • easy answer... by patazathoth (Score:1) Monday May 20 2002, @07:19AM
  • Good naming is the foundation by whipping_post (Score:1) Monday May 20 2002, @07:22AM
  • Tons of code already there by 192939495969798999 (Score:1) Monday May 20 2002, @07:26AM
  • input output specs by yzquxnet (Score:2) Monday May 20 2002, @07:30AM
  • Overview by mathematician (Score:1) Monday May 20 2002, @07:30AM
  • Peer review by oliverthered (Score:1) Monday May 20 2002, @07:31AM
  • Comment describe Why you did it by DickLieber (Score:1) Monday May 20 2002, @07:33AM
  • The common Joke by msheppard (Score:2) Monday May 20 2002, @07:39AM
  • It's simple by DaKritter (Score:1) Monday May 20 2002, @07:44AM
  • Important!! by Zapper (Score:1) Monday May 20 2002, @07:44AM
  • C++-specific stuff by Permission Denied (Score:2) Monday May 20 2002, @07:44AM
  • in defense of poorly commented code by FeltTip (Score:1) Monday May 20 2002, @07:50AM
  • Any comment... by akh (Score:1) Monday May 20 2002, @07:51AM
  • THE Simplest rule for writing good comments. by bteeter (Score:1) Monday May 20 2002, @07:54AM
  • State the rationale. And DOCUMENT THE DIRT. by dpbsmith (Score:2) Monday May 20 2002, @08:00AM
  • My number one rule: say _why_ by Chiwo (Score:1) Monday May 20 2002, @08:01AM
  • Golden Rule (Score:3, Insightful)

    by Salamander (33735) <slashdot@@@pl...atyp...us> on Monday May 20 2002, @08:02AM (#3549648) Homepage Journal

    The most important thing wrt to commenting code is to put yourself in the reader's shoes. What would that reader need to know that's not obvious from the code? One useful exercise is to pretend that you're leaving your job and you're doing a brain-dump for the (reasonably bright) person who will inherit your code. Your goal is to anticipate every question they ask or suggestion they make, in the form of a comment. If they're likely to ask what something does or how it works, add a comment. If you add code to fix a specific bug then add a comment; obviously you didn't recognize the need for that code at first, or else there wouldn't have been a bug, so the next person probably won't either unless you comment it. If they're likely to say "this would be better if xxx" but you already tried xxx, put in a comment that says "we already tried xxx but it didn't work because..." IMO that last is the single most useful kind of comment because it saves someone from going down a blind alley. BTW, the same "role-playing" approach works really well for specs too.

    Another important skill is knowing when not to comment something. If it's blazingly obvious what something does and how/why it does it, don't comment it. If there are too many comments, the person reading the code will often decide that reading the comments is a waste of their time and they'll just start ignoring them. Then they'll miss the one comment that really does matter. If you must be verbose in your commenting, at least use some sort of visually obvious marker for really important "you'll break it if you ignore this" kinds of comments, to distinguish them from the less important stuff.

    Lastly, don't be afraid to spice up your comments. Be totally candid about stuff - yours or someone else's - that you think is brain-dead. Make wisecracks and in-jokes, within the bounds of good taste and brevity. People are more likely to read your comments if they can occasionally get a chuckle out of them. They're more likely to enjoy working on your code, and speak well of it/you when asked. These are all good things - for you, for them, for your employer or client. Coding can be dreary enough without robotic comments.

  • Identify the Audience by thelen (Score:1) Monday May 20 2002, @08:04AM
  • Sample C++ Coding Standard by camelcai (Score:1) Monday May 20 2002, @08:10AM
  • always_false // when false there are no comments by tlh1005 (Score:1) Monday May 20 2002, @08:17AM
  • What... by Greyfox (Score:2) Monday May 20 2002, @08:18AM
  • Well commented code by diacopo (Score:1) Monday May 20 2002, @08:18AM
  • ...Fantasy! by Tephyrnex (Score:1) Monday May 20 2002, @08:20AM
  • Reminds Me ... by graphicartist82 (Score:1) Monday May 20 2002, @08:22AM
  • references to specification by ammoQ (Score:1) Monday May 20 2002, @08:24AM
  • fusebox by gavlil (Score:1) Monday May 20 2002, @08:24AM
  • unless your company is run by idiots by AssFace (Score:1) Monday May 20 2002, @08:28AM
  • Well-commented code by beth_linker (Score:2) Monday May 20 2002, @08:33AM
  • Names by Art_XIV (Score:2) Monday May 20 2002, @08:37AM
  • Pseudocode comments by mlas (Score:1) Monday May 20 2002, @08:42AM
  • There is a missing level of documentation by gradbert (Score:1) Monday May 20 2002, @08:46AM
  • german comments by beddess (Score:1) Monday May 20 2002, @08:51AM
  • Beagle Bros, Apple II, and Memory Lane... by teamhasnoi (Score:1) Monday May 20 2002, @08:54AM
    • Memories!!... by Hoi Polloi (Score:2) Monday May 20 2002, @09:22AM
  • Another great book by KFury (Score:2) Monday May 20 2002, @09:01AM
  • Look at the comments for SWISH++ by pauljlucas (Score:1) Monday May 20 2002, @09:02AM
  • Comments as a method for covering your butt. by MSUWalt (Score:1) Monday May 20 2002, @09:05AM
  • KISS stands for many things... by janda (Score:1) Monday May 20 2002, @09:10AM
  • "why" is more important than "what" by NickDoulas (Score:1) Monday May 20 2002, @09:15AM
  • This will lose you points at CMU... by Lethyos (Score:2) Monday May 20 2002, @09:31AM
  • Three levels of comment by Chacham (Score:1) Monday May 20 2002, @09:33AM
  • "Design Intent" a.k.a. "why" by SledgeHammerSeb (Score:1) Monday May 20 2002, @09:34AM
  • To me... by hackwrench (Score:1) Monday May 20 2002, @09:35AM
  • Why, not what by andy@petdance.com (Score:2) Monday May 20 2002, @09:36AM
  • Code Review by tarsi210 (Score:2) Monday May 20 2002, @09:37AM
  • "The Practice Of Programming" by replica (Score:1) Monday May 20 2002, @09:44AM
  • How To Write Unmaintainable Code by snowtigger (Score:1) Monday May 20 2002, @10:05AM
  • "Why" not "what" by Mr. Fred Smoothie (Score:2) Monday May 20 2002, @10:13AM
  • My list (Score:4, Interesting)

    by edp (171151) on Monday May 20 2002, @10:15AM (#3550764) Homepage

    One purpose of comments is to explain the code to another engineer (including oneself in the future). Another purpose is to demonstrate the code works, whether an informal argument that the code does what it should or a mathematical proof. These two purposes have different needs.

    For the former case, standard writing rules apply. Decide who the audience is. I often figure the audience is an engineer who knows the type of programming at hand, but doesn't know what is done by this particular code, and may or may not be familiar with the product, depending on circumstances. Knowing the audience tells you what assumptions to make and what has to be explained, either by prose or by giving directions to reference material.

    Write complete, grammatically correct sentences. This goes a long way to making comments comprehensible. Sometimes a little phrase won't be understood because the reader can't fill in the unwritten parts, or because there's ambiguity in the wording. It is okay to use short phrases when describing objects being defined or declared (e.g., "number of links to this object" or "dollars owed this customer), but keep the context in mind. Introduce the compound object with sentences where appropriate.

    "Dollars owed this customer" reminds me -- use units. Don't write "Money owed this customer" or "time since last update." Specify seconds or milliseconds, not time. Document how the object models whatever it is modeling. That may be a physical thing like time or a conceptual thing. E.g., if a pointer connects one object to another, document the relationship that represents. If a "debt" class contains a pointer to a "person," don't document it as "person associated with this class." Document the relationship -- this particular pointer may represent the debtor, the creditor, the escrow agent, or somebody else.

    Give context. I have seen thousands of modules that just leap into code with no explanation of what they are. Even if the comments say what a function does, a reader might not really understand it until they know what it is used for. Document where the code fits into the bigger scheme and what it is used for. Give the reader context so the purpose of the function makes sense. Even if a complete mathematical description of a function is given, so that the reader can precisely predict its behavior in every situation, it might not make sense to the human mind until they have a mental image or model of it.

    For the second purpose, demonstrating the code works, explain how the code implements an algorithm. It's not enough to explain what the steps are doing; you need to show how the total result comes out of the algorithm, unless it is something simple or familiar. E.g., a formal description of the long division taught in elementary school would generally be incomprehensible. "Find the largest digit d such that d times q is less than r[i]. Subtract d*q from r[i] to get r[i+1]. Append d to output..." Nobody seeing that for the first time would understand what it is doing, even if all the steps were clear. Even if you explained each step and explained the result, it won't be clear to some readers how the steps produce the result, so explain that.

    Document alternatives that weren't chosen, and the reasons why. If you were tempted to implement algorithm X but found you had to do Y because some error might occur, record that information. Otherwise, somebody working on the code next year might see your longer code for Y and change it to X without realizing the problem.

    This isn't intended to be a complete list, just what occurred to me at the moment.

  • Self-documenting code needs little comment by werdna (Score:2) Monday May 20 2002, @10:16AM
    • 1 reply beneath your current threshold.
  • Refactoring may be better by trajano (Score:1) Monday May 20 2002, @10:18AM
  • Knuth - Literate Programming (Score:3, Insightful)

    by goodviking (71533) on Monday May 20 2002, @10:20AM (#3550810) Journal
    Some variation of the methods described in "Literate Programming" [stanford.edu] by Donald Knuth [stanford.edu] are a good place to start. In summary, Knuth says that you should be able to extract from the same source both machine instructions, and a human parsable document, with unusually high importance placed on the later. Whether or not you want to imbed LaTeX [latex-project.org] into your document is up to you (I never have bothered), but on the whole find something that will make your code and algorithms understandable to another programmer who's never met you (because that's probably who will be either grading or maintaining your code at some point).
  • Sometimes they just dont grok it. by crovira (Score:2) Monday May 20 2002, @10:20AM
  • They'll always complain.... by pjrc (Score:2) Monday May 20 2002, @10:22AM
  • Happy medium by davebooth (Score:2) Monday May 20 2002, @10:23AM
  • Experience, Comments, and Design Patterns by Bouncings (Score:2) Monday May 20 2002, @10:25AM
  • Well-commented code by YellowElf (Score:1) Monday May 20 2002, @10:28AM
  • Primary audience of code is other programmers by p3d0 (Score:2) Monday May 20 2002, @10:32AM
  • Make your code readable! by UncleRoger (Score:2) Monday May 20 2002, @10:34AM
  • Recommended Classic by Genus Marmota (Score:1) Monday May 20 2002, @10:35AM
  • Comment the WHY or the HOW and not the WHAT by angel'o'sphere (Score:2) Monday May 20 2002, @10:40AM
  • When I get bored... by Rorschach1 (Score:2) Monday May 20 2002, @10:46AM
    • 1 reply beneath your current threshold.
  • Comments in Code by Simonetta (Score:1) Monday May 20 2002, @10:51AM
  • learn from the masters... by carpe_noctem (Score:1) Monday May 20 2002, @11:11AM
  • My naming convention by NibbleAbit (Score:1) Monday May 20 2002, @11:20AM
  • To me it means ... by grgcombs (Score:1) Monday May 20 2002, @11:24AM
  • My 2 cents... by MrIcee (Score:1) Monday May 20 2002, @11:25AM
  • Personal commenting practices by franknagy (Score:1) Monday May 20 2002, @11:35AM
  • Logging = good comments by irritating environme (Score:1) Monday May 20 2002, @11:35AM
  • Have a team standard by sohp (Score:2) Monday May 20 2002, @11:49AM
  • Principles and Motivation by SEGV (Score:1) Monday May 20 2002, @12:06PM
  • Javadoc by anonymous_wombat (Score:1) Monday May 20 2002, @12:06PM
    • Re:Javadoc by SilentStrike (Score:1) Monday May 20 2002, @06:53PM
  • post and pre conditions! by viperstyx (Score:1) Monday May 20 2002, @12:17PM
  • Architecture and Flow of Control comments by Random Man (Score:1) Monday May 20 2002, @12:27PM
  • If it needs comments, it's not well-written by KC0A (Score:1) Monday May 20 2002, @12:32PM
  • While we're all talking about DEVELOPERS... by SlapAyoda (Score:1) Monday May 20 2002, @12:39PM
  • blame the slacker in me by i chose quality (Score:1) Monday May 20 2002, @12:41PM
  • As this will never be seen by the like of man... by feloneous cat (Score:2) Monday May 20 2002, @12:52PM
  • Javadoc is great training. by Java Ape (Score:1) Monday May 20 2002, @12:54PM
  • Coding comments by VG_slash (Score:1) Monday May 20 2002, @12:58PM
  • Some useful pointers... by ktohk (Score:1) Monday May 20 2002, @01:03PM
  • Comments by counterexample (Score:3, Informative)

    by slamb (119285) on Monday May 20 2002, @01:05PM (#3552164) Homepage

    Take a look at these files [uiowa.edu]. This project is basically an example of what not to do. It's faggotted up like a twelve-year-old schoolgir's notebook, to borrow a phrase from The Onion. In particular,

    • The huge block comments have these banners that are at column 1, in complete defiance of the indentation. Consequently, the indentation is not at all consistent across the code. It makes it difficult to visually see what level you are at. It makes using a folding text editor impossible.
    • there are lots of comments along the lines of "// slamb was here, 4-26-02". These are things much more appropriate for a version control system (cvs annotate). They clutter up the code unnecessarily.
    • the comments that are there explain nothing. For example,
      // This is the main method that Java invokes at start-up

      That should be obvious from the "public static void main (String argv[])".

    • They are not in the proper form for Javadoc, Doxygen, or any other documentation generator. If you go to the trouble of putting comments at the beginning of methods in structured way, you should do so in a way that can be used to generate easily browsable documentation. See Writing Documentation Comments [sun.com] at Sun.
    • The grammar is inconsistent and awkward. That same document gives hints on making useful documentation with grammar that does not distract.
    • The code is not self-documenting. If you adhere to a consistent coding standard, like Sun's Code Conventions [sun.com], you will know what a lot of stuff is without resorting to comments at all.
  • Don't stop at well-named variables by Leomania (Score:1) Monday May 20 2002, @01:23PM
  • good tools by technomom (Score:1) Monday May 20 2002, @01:36PM
  • Well-Commented Code by Anonymous Coward (Score:1) Monday May 20 2002, @01:40PM
  • Wait till you've almost forgotten it (Score:3, Insightful)

    by vanyel (28049) on Monday May 20 2002, @01:49PM (#3552537) Journal
    Unfortunately, this is rarely practical, but I find the most useful comments are written when I'm going back through code I wrote over a week ago. The reasons for doing things are no longer on the surface, and thus if there's something I look at and have to dig for understanding, then it needs better explanation.
  • First, use a good language... by frank_adrian314159 (Score:2) Monday May 20 2002, @02:09PM
  • No such thing. by llzackll (Score:1) Monday May 20 2002, @02:41PM
  • Comment architecture, not code by StupidFodder (Score:1) Monday May 20 2002, @04:02PM
  • why, not what by moocat2 (Score:1) Monday May 20 2002, @04:02PM
  • Coding Style by Sir Robin (Score:1) Monday May 20 2002, @04:34PM
  • No comment - seriously... by tz (Score:1) Monday May 20 2002, @04:52PM
  • Variable name length by vrmlguy (Score:2) Monday May 20 2002, @04:56PM
  • Documentation of Architecture and Standards by AShocka (Score:1) Monday May 20 2002, @04:56PM
  • Variable name lenght (redux) by vrmlguy (Score:2) Monday May 20 2002, @05:00PM
  • It's an art.... by beaviebugeater (Score:1) Monday May 20 2002, @05:30PM
  • Refactoring, by Martin Fowler by smallstepforman (Score:2) Monday May 20 2002, @06:18PM
  • can be a godsend, but... by PhilJackson (Score:1) Monday May 20 2002, @06:19PM
  • would be geek? by sister_snape (Score:1) Monday May 20 2002, @06:33PM
  • Use What's Already Out There by gviamont (Score:1) Monday May 20 2002, @06:35PM
  • The Practice of Programming by troels (Score:1) Monday May 20 2002, @07:02PM
  • Why, not what! by Snoopy77 (Score:1) Monday May 20 2002, @07:05PM
  • Get a Style Guide by aebrain (Score:1) Monday May 20 2002, @07:37PM
  • Can you imagine... by booms (Score:1) Monday May 20 2002, @08:08PM
  • HP75 design spec comments by codesmithe (Score:1) Monday May 20 2002, @08:38PM
  • Propper comentations by MoneyT (Score:2) Monday May 20 2002, @09:08PM
  • C++ Variables by finity (Score:1) Monday May 20 2002, @10:15PM
  • curl-up with a good comment by hasitwho (Score:1) Tuesday May 21 2002, @03:08AM
  • How To Write Unmaintainable Code by Max Threshold (Score:1) Tuesday May 21 2002, @04:49AM
  • IMHO... by Anonymous Coward (Score:1) Thursday May 23 2002, @09:21AM
  • Re: Comments are evil. by dorward (Score:2) Monday May 20 2002, @03:37AM
  • Re:Comments are evil. by ggeens (Score:1) Monday May 20 2002, @04:21AM
  • Re:Comments are evil. by Iffy Bonzoolie (Score:1) Monday May 20 2002, @04:26AM
  • Re:Comments are evil. by bullgod (Score:1) Monday May 20 2002, @05:25AM
  • Re:commenting bad. by Fnagaton (Score:1) Monday May 20 2002, @06:19AM
  • No comments? by pommiekiwifruit (Score:1) Monday May 20 2002, @06:34AM
  • Re:Less comments better code by mauriciosl (Score:1) Monday May 20 2002, @09:05AM
  • 67 replies beneath your current threshold.
(1) | 2 | 3