Slashdot Mirror


What is Well-Commented Code?

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

53 of 802 comments (clear)

  1. Code Complete by kimba · · Score: 5, Informative

    I can absolutely recommend a book called Code Complete. 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.

    1. Re:Code Complete by NewtonsLaw · · Score: 5, Insightful

      I can absolutely recommend a book called Code Complete [amazon.com]. Yes, it is published by Microsoft

      Yes, that's on my bookshelf -- but, given the fact that they go to great lengths to point out the importance of checking for buffer over/under-runs and fencepost errors, one can't help wondering if (in the wake of all those critical bugs in IE/Outlook/IIS) any of Microsoft's own programmers have read it.

      More "do as we say, not as we do" from Microsoft?

    2. Re:Code Complete by jsse · · Score: 3, Funny

      Yes, it is published by Microsoft

      *Abruptly stops the finger from clicking the link*

  2. Describe before you apply by inflex · · Score: 3, Funny
    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.
    }

    1. Re:Describe before you apply by spongman · · Score: 3, Interesting
      how about while (true) { ?

      1) It reads right in english.
      2) It's type-safe in C++ for -Wall.
      3) It doesn't use antequated or obfuscated C-isms.

      I can't stand things like:
      #define ever ;;
      ...
      for (ever) {

  3. Good Comments by jamieo · · Score: 4, Insightful

    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.

    1. Re:Good Comments by Cederic · · Score: 4, Insightful


      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

    2. Re:Good Comments by MadAndy · · Score: 5, Insightful
      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.

    3. Re:Good Comments by Simon+Brooke · · Score: 4, Insightful
      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.

      --
      I'm old enough to remember when discussions on Slashdot were well informed.
    4. Re:Good Comments by jamieo · · Score: 3, Interesting

      I agree with the "increment loop counter" comment, that isn't worthwhile at all - but that's the difference between good and bad comments ;)

      However, I completely disagree with your premise about this being a maintenance nightmare and doubling workload.

      It's the exact opposite of a maintenance nightmare - it helps maintenance (certainly for long running large projects with developer turnover).

      It's also very little overhead. If you are a professional developer, just count how many hours you really write code in a week of working. It's not a great deal really, and the added time to add good comments is very little. The rewards of doing it are far greater than any costs.

      This is a complete mindset thing, just like coding standards - if you get in the mindset, it's easy and no cost, if you moan and complain and fight them all the time it's a pain and loads of work.

    5. Re:Good Comments by ClarkEvans · · Score: 3, Insightful

      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.

      The comments should talk about _what_ the module dues, not _how_ it does it. Stick with this distinction and it'll be a bit easier. If your module changes so much that the _what_ changes... then you really should take the time to reconsider your comments... as they may point out what assumptions other code may be making and where compensating changes may be needed.

  4. Use plenty of expletives by oingoboingo · · Score: 5, Funny

    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.

    1. Re:Use plenty of expletives by Zocalo · · Score: 3, Funny
      Well the linux kernel certainly qualifies then...

      [admin@frodo linux-2.4.9-31]# grep -r [Ff][us]ck * | wc
      134 1327 10723
      Detection of the other expletives is left as an exercise for the reader...
      --
      UNIX? They're not even circumcised! Savages!
    2. Re:Use plenty of expletives by Anonymous Coward · · Score: 4, Funny

      Until someone runs nm on your executable and finds some "funny" variable names.
      Funny variable names are sometimes related to say specific bugfixes a certain individual or customer has demanded.

      I know one person where very large customer demanded a specific and very idiotic new feature to the software, due to the customer being an idiot.

      Executable was not stripped.

      The variable name to control this feature in certain functions was thus called IsAFuckingIdiot .

      Customer by convention always ran nm on all new executables they installed.

      Customer got very upset.

  5. Doxygen, etc by Stary · · Score: 5, Informative

    Tools like javadoc, or maybe better in your case doxygen 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.

    --
    Tomorrow will be cancelled due to lack of interest
  6. It's been a long time but.. by NewtonsLaw · · Score: 5, Interesting

    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.

    1. Re:It's been a long time but.. by emag · · Score: 3, Interesting

      This is a technique I hope to follow with a few "personal" projects that I'm about to start. I'm refusing to write any code until I get down at least a spec for what each section is supposed to be doing.

      Alas, since the UI is wholly divorced from the back-end (I discovered I'd designed in my head an n-tier system just by seeing what I hated about both similar and unrelated software I've been forced to work with), I'm not sure I could follow everything precisely the way you suggest. After all, in the overall design, there will actually be several clients, each displaying data appropriate to its interface (web vs. fat client vs. text vs. scripted API vs. ???). I know what I can, and in fact must, do is define just how the "back end" (in terms of the clients) tells the clients what to display, what to get from the user, etc.

      I've also got to point out that in the past, I've been guilty of the "jump right in and code immediately" method of development. Unfortunately, I didn't have much in the way of control, since we were under pressure from both upper management and the customer (they have a lot of boats and guns...) to produce code for testing immediately.

      Even though this was for a "next generation" of a system already in place, it was a complete rewrite in a language the customer wasn't all that familiar with (C++), and so they were concerned that we wouldn't be able to guarantee anything would even work, let alone within the tight timing constraints required by parts of the overall system that weren't being changed.

      We had to deal with collecting all sorts of assinine metrics, such as the SLOC (Source Lines of Code) you've mentioned. Of course, the number of comments was also a metric that needed to be collected, and so we somehow had to find time to do those while frantically trying to keep pace with specs that seemed to change arbitrarily on a weekly or monthly schedule. Assinine? Yes. Real life? Yes. The only saving graces were that we'd managed to convince everyone who made decisions that some ridiculously low SLOC count was what we were responsible for in terms of monthly performance (giving us some breathing room to do intelligent design), and regular (weekly) code reviews amongst all the developers, spec writers, and the customer, to verify that what we were doing was, in fact, correct. (Though it seemed at times that we spent the majority of the meetings teaching all of the non-developers how to code in C++)

      --
      "The urge to save humanity is almost always a false front for the urge to rule." --H.L. Mencken
    2. Re:It's been a long time but.. by Cederic · · Score: 3, Insightful


      Yes, we can tell it's been quite a while.

      Right now, businesses go to their IT teams and say "We need software that does X. Deliver it in 8 weeks."

      It would take 8 weeks to write a structure document in the manner you are describing (especially going through the various top-down iterations to reach code).

      Instead we have to write the basic framework of the solution, get that ready in four weeks, and then change and tweak all the little pieces of functionality that have changed in the requirements since we started. Because businesses don't know what they want, and all that is definite is the go live date (usually because the Marketing team have a fixed launch date)

      How are you meant to pre-document a requirement that arrives three days before go-live? With a suitable methodology you can add it, test it, and regression test the rest of the system to be sure you haven't broken it. But then generating user documentation too? Dream on, that's going to have to wait.

      ~Cederic

    3. Re:It's been a long time but.. by noom · · Score: 3, Interesting


      That style of programming leads to unreadable and unmaintainable code. The problem is that, in many cases, the programmer that required reams of documentation in order to write the code also requires that documentation in order to read it. The system-level become inappropriate to the evironment and language being used since the design was done "in your head" instead of "in the code.

      IMHO, detailed specs should only be done when there can be a GAURANTEE that it won't change for at least 2 years. The is is the usually the case with specs produced by groups like W3C, IETF, or the OMG, and a lot of programmers think they should copy the activities of these beauricratic organizations in their own work, where requirements can be expected to change continuously. In this environment, maintaining a detailed specification that is separate from the code is far too impractical. It's better that programmers make the code and the focus of their attention and make sure their code *deserves* to be the focus of attention (i.e. it's well written, elegant, easy on the eyes and mind, fun to take walks on the beach with, etc...).

      -n00m

    4. Re:It's been a long time but.. by sbeitzel · · Score: 3, Interesting
      Well, it sort of depends on what kind of code you're writing, doesn't it? In applications development, the dev cycle can be 1 year long or longer, with support cycles that run about 3 to 6 months.

      In web development, your dev cycle is often 3 months or fewer, with support cycles measured in days or even hours. The practice of shifting requirements up until the ship date is one that we, as professionals, have a duty to curb. If you're implementing new requirements during the final 10% of the project, then you're allowing the customer to break the project and blame you.

      Unfortunately, the nature of programming doesn't really change between those extremes: it's still a question of figuring out what the problem (the product requirements) is, designing a solution to the problem (writing a spec and, hopefully, designing it so that three cycles from now when you get a requirement to change the product, you can), and then writing the code that implements the design.

      The comments we always see in these discussions along the lines of, "comments are for the weak; real programmers don't use comments..." don't take into consideration the fact that the odds are very good that you won't be supporting your own code in a year, you'll be dealing with someone else's crap. As professionals, it behooves us to provide as many clues as we can to the poor sods who'll follow after us -- because what goes around, comes around.

      When I'm doing really fast web development, the spec is often a drawing on a white board -- so I take a picture. The design is often a doodle in a notebook -- which I label and keep on my bookshelf. And when I start banging out code, the first thing I do is pseudocode in comments, then interleave the real thing. That way, when I'm interrupted in the process, I can pick up again quite easily.

      I've handed off a lot of code to other people, and I've never gotten any complaints about too many comments (or about useless ones). I have gotten comments about how easy it is to follow what I'm doing, and that's enough. Do what you need to do to get the job done, but keep in mind that the job doesn't stop with getting the thing to compile and link.

      --
      Oh, go on, check out my job.
    5. Re:It's been a long time but.. by mrdlinux · · Score: 3, Informative

      What you are describing (and quite well) is the top-down programming practice. There's a big problem with it, though: in the real world, things change. As others have pointed out, you can't be guarenteed to be able to hammer down a specification that will be satisfactory for a year, or a month, sometimes even a week or a day. Some customer, some manager, or whoever, will demand a change in the final product. What will you do then? You will have to change your entire structure around and that can be extremely difficult.

      Fortunately there are other ways of approaching the problem. One of them is called the bottom-up approach. The basic idea is to create a mini-language that one can better formulate your problem in, and then start putting the pieces together. This is complimented by dynamic semantics that languages such as Common Lisp or Smalltalk have. Incremental, interactive compilation and development is well supported by these environments. The code winds up being self-documenting because you wrote it in a mini-language! Weirdly obfuscated--but necessary--as well as commonly used pieces of code can be abstracted with Lisp macros. Changing your data-structures is no problem, already in-use data-structures can be dynamically updated (and you can control how it happens). Errors are handled by the exceptional condition system (no pun intended) and the program can be continued from where you left off, after being fixed. Always you have a working, running codebase.

      --
      Those who do not know the past are doomed to reimplement it, poorly.
  7. Re:Variable Names by gazbo · · Score: 4, Insightful
    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?

  8. Document the function's contract by IvyMike · · Score: 5, Interesting

    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:)

  9. Examples.. by popeyethesailor · · Score: 5, Funny
    # 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 for further details:)
  10. Multiple passes to your code by fractaltiger · · Score: 4, Insightful

    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.

    --
    "Wireless : LAN :: Laptop : Desktop"
  11. PDL it is good no? by ZanshinWedge · · Score: 3, Interesting

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

  12. Linux and other things. by jon_c · · Score: 4, Insightful

    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.

    --
    this is my sig.
  13. Re:Variable Names by emag · · Score: 5, Insightful

    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.

    --
    "The urge to save humanity is almost always a false front for the urge to rule." --H.L. Mencken
  14. Re:type* var is evil by emag · · Score: 5, Insightful
    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...)
    --
    "The urge to save humanity is almost always a false front for the urge to rule." --H.L. Mencken
  15. Re:Simple rule of thumb by nagora · · Score: 4, Interesting
    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

    --
    "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
  16. Comments Considered Harmful by Bazzargh · · Score: 3, Interesting

    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

    1. Re:Comments Considered Harmful by Bazzargh · · Score: 3, Interesting
      I see you've gone back on the post a little later but its worth answering some of your points.

      Yunno, I'm really getting sick of Fowler's "worse is better" nonsense trying to win back the day for "cowboy coders" who can't handle any discpline at all and want to treat critical production code as a playground.

      Fowler's stuff isnt cowboy at all. It actually takes a lot of discipline to follow what he actually says in his book (writing tests to ensure that each refactoring is safe). His book is a series of recipes for how to introduce changes safely, not a rally call for changing code because you feel like it today. The Refactoring book can help people working in any methodology (except perhaps the 'Personal Software Process' and its variants, which want you to learn to write code right first time, and are less realistic for code maintenance). XP gets a mention but its not an XP book.

      Meaninglessly vague. Is javadoc boilerplate?

      Meaning 1 on wordnet is "a standard formulation of legal documents or news stories". Now look at this (code from Tomcat). See the boilerplate comment at the top? Its NOT THE JAVADOC - its the license. There are tools like jalopy which help you maintain this cruft but like I say it helps noone but lawyers.

      This guy must have a massively cool source control tool that actually shows him the changelog on a per-function basis, and automatically senses and shows only the changes that are significant, like an interface change.

      The 'change history comment' is the old practice of writing in a history of changes at the top of the file (not on a function by function basis as you suggest) duplicating the comment recording in the source code control system, while not necessarily recording all changes because it isnt /driven/ by that system. VSS, CVS, etc can show you the changelog externally, or you can include a $Keyword$ to get the changelog included in the comment and maintained for you. As for knowing which change is significant - developers don't know this either. The change which breaks things is the significant one and they usually don't realise they've done it at the time. Interfaces changes, while high cost, are actually less significant causes of error since they are easily caught by static checks. It is the changes in behaviour that will get you.

      We don't always get to write everything from scratch...

      This is true. often you'll not get to rename the methods of some dumbly named third party interface. And in this case the comment is inevitable. Note I did say not all comments are bad. I'm asking you to question them.

      Another smaller, uncommented method no doubt.

      Yes, exactly. If the smaller method is 4 lines long, has a blindingly obvious name, and is in the private interface of the class (often the case for extracted methods like this), the comment is superfluous.

  17. My favorite comments by bentini · · Score: 5, Funny
    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

  18. like a book on nutrition by g4dget · · Score: 3, Insightful
    Code Complete and similar books strikes me as being a bit like books on nutrition and dieting: they tell you what is good for you and they give you some tips on dieting. But most people who read them end up eating junk food anyway because they just don't have the time to do it right.

    By all means, read Code Complete--its suggestions are sensible. But the real culprit when it comes to poor software are time and resource pressures, feature creep, and other environmental factors. Maybe at least the book will let you recognize when your project is doomed and leave; McConnell seems to have done that--he isn't at Microsoft anymore.

  19. Re:type* var is evil by tal197 · · Score: 3, Informative
    OTOH, char* foo is arguably more logical than char *foo. You are declaring foo as being of type "character pointer". You are not, in fact, declaring a char with a pointer to it named foo (you never declared the char, only the pointer), which is what is implied by your recommended form.

    *foo means 'foo dereferenced'. In a type declaration, 'int foo' means 'foo is an int', so 'int *foo' means 'foo dereferenced is an int'. And, therefore, foo is a pointer to an int.

    So, it's actually quite logical. In this: 'char foo, *bar', we declare that two things have type 'char': foo, and the thing that bar points to.

  20. Re:Variable Names by Grab · · Score: 5, Interesting

    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.

  21. Things to bear in mind by Rogerborg · · Score: 5, Insightful
    • 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.
    --
    If you were blocking sigs, you wouldn't have to read this.
  22. Re:Coding Standards by GigsVT · · Score: 3, Funny

    Other things, such as always including { and } in C, and putting them alone on their own line

    Phew, I thought I was alone. I'm glad it makes sense to someone other than myself to actually have the braces line up vertically.

    --
    I've had enough abrasive sigs. Kittens are cute and fuzzy.
  23. Favor Code Clarity Over Comments by Bob9113 · · Score: 5, Insightful

    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.

  24. Re:Comments are evil. by Anonymous+Brave+Guy · · Score: 3, Insightful
    Actually, if your variables and functions names are meaningful you DON't NEED Comments.

    Sorry, but that's just not true.

    You need fewer comments if your identifiers are well-chosen, certainly. But I've never seen a significant piece of code that would be adequately described by well-chosen identifiers alone.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  25. Re:Make the variable names mean something! by Mr.+Slippery · · Score: 5, Informative
    If a method has more than a screen full of code (i.e. about 20 lines), split the method into multiple methods

    I strongly disagree. The proper delineation of a function or method is the operation that it abstracts, not how long it is.

    If a subroutine is only called once, and doesn't cleanly abstract some idea (i.e., if you can't tell me what it does in one simple sentance), it should not be in a separate subroutine.

    I've seen too much code written in the manner you suggest, that makes the reader bounce around from function to function to function for no reason other than "otherwise that function would be more than 30 lines".

    void foo()
    {
    foo_part_1();
    foo_part_2();
    foo_part_3();
    }

    If I have to maintain such code I always refactor it into one subroutine.

    --
    Tom Swiss | the infamous tms | my blog
    You cannot wash away blood with blood
  26. Re:Timeless Prof D.Knuth says it best... by tslarkin · · Score: 3, Insightful

    Literate programming is to comments what a high level language like Pascal is to assembly language.

    Programmers have the weakness of thinking that they are writing for a compiler. They should be imagining that they are writing for another human reader. This is the essence of literate programming, which is, in my opinion, the only good idea that anyone has ever had about program documentation.

    If the programmer is restricted to interspersing comment lines between lines of code, then the elaboration of the documentation must follow the sequence of the code. To use a simple example, if I write a class definition, then I must declare all the member variables within the block of text that begins "class foo" and ends with "};". However, that may not be the best way to explain the significance of those variables. Maybe it would make more sense (for the human reader) to delay the declaration of a member variable until the place where it is first used. This can easily be done with CWeb. This simple example is hardly sufficient to reveal the power of LP. It is well worth taking a serious look.

    After the literate program is written, it is processed by two other programs. One produces a file suitable for submission to a compiler. The other produces a TeX file, which outputs a properly formatter version to be read by a human.

    The code itself is never the best documentation. It's not documentation at all, except in the most trivial cases.

    Any programmer can write a literate program. It's just a matter of understanding who his audience is.

  27. Re:Variable Names by jeremyp · · Score: 3, Insightful

    There's a third thing the maintainer needs to know which is "what it's *supposed* to do. Comments are invaluable for that. Consider the following C code fragment:

    for (i = 1 ; i ARRAY_SIZE ; ++i)
    {
    do_something_to (array [i]) ;
    }

    Why isn't it doing something with element 0?
    Now look at these two fragments

    /* Do something to all elements in array */

    for (i = 1 ; i ARRAY_SIZE ; ++i)
    {
    do_something_to (array [i]) ;
    }

    and

    /* Do something to all elements in array except */
    /* the first one because... */

    for (i = 1 ; i ARRAY_SIZE ; ++i)
    {
    do_something_to (array [i]) ;
    }

    Just by adding a one line comment, a bug has been exposed, or the maintainer has been prevented from inserting a bug in the second instance.

    As a maintainer, I'd want to be able to see what the code does (well set out, good structure, descriptive names etc) and what the programmer meant it to do, i.e. good comments.

    Anybody who puts jokey unhelpful comments in their code should be aware that these will inspire feelings of hatred and extreme violence towards them in the maintainer who has two hours to fixe the air traffic control system before the 747s start falling out of the sky.

    --
    All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
  28. Re:Variable Names by SecurityGuy · · Score: 3, Funny

    Bah, he was hard to work with, he was easy to terminate.

  29. My list by edp · · Score: 4, Interesting

    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.

  30. It's sophomores like you... by Pollux · · Score: 5, Informative

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

  31. Knuth - Literate Programming by goodviking · · Score: 3, Insightful

    Some variation of the methods described in "Literate Programming" by Donald Knuth 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 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).

  32. They MUST vs. they WON'T by Mr.+Fred+Smoothie · · Score: 3, Insightful
    One of the great insights of the Agile Software Development movement, if you ask me, is the realization that a process which doesn't take into account the strengths and weaknesses of the people who will use it is flawed.

    So, it's one thing to say "if they change the code, they MUST change the comments", but realize that unless you have the ability to force the issue (a tool to make you change comments before saving changes, managers who care more about firing programmers who don't follow code standards than avoiding schedule slippage -- hint: I've never seen one of these, EVER), 9 times out of 10, they just won't do it. It's like teaching abstinance as a method of reducing teen pregnancy.

    Thus, the practice of having comments which are redundant w/ the code is simply setting the project up for failure as the parent poster pointed out.

    --

  33. Doc & code sync always drifts! by Mr.+Fred+Smoothie · · Score: 3, Insightful
    So what happens when the code changes and breaks the assumptions so fastidiously outlined in the documentation?

    It's less of an issue w/ Javadoc and Doxygen comments (which is embedded in the code) than external documentation, but the fact is that managers reward code changes, not documentation changes, and programmers are lazy.

    Until you can change these basic, simple facts, what are you going to do? One strategy is to encourage self-documenting coding standards as well as encourage documentation updates. But people NEED to remain aware of the basic principle that the only authoritative documentation is the source code itself.

    --

  34. Comments by counterexample by slamb · · Score: 3, Informative

    Take a look at these files. 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 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, you will know what a lot of stuff is without resorting to comments at all.
  35. Wait till you've almost forgotten it by vanyel · · Score: 3, Insightful

    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.

  36. You are a moron by RelliK · · Score: 3, Interesting

    1. Your "improved" code is much less readable than the original. Whoever has to maintain it will need more time to comprehend it.

    2. You introduced a bug on line 3 (null pointer dereferencing).

    Yes, I have personally seen code like it and I wanted to shoot the fucking idiot who wrote it.

    --
    ___
    If you think big enough, you'll never have to do it.
  37. Better practice-- inline comments tell why not how by einhverfr · · Score: 3, Insightful

    Functions should have their arguments documented-- what they mean and what they do, and their return values documented. That is sufficient.

    Inline comments have a place, but they are way over used. If you are telling me how your program works using inline comments, I will ignore those comments becuase if there is a problem, your code may not behave as advertized.

    Instead inline comments should document WHY you do something a certain way and help me to understand what problems caused a particular piece of code to us a particularly clumsy algorythm or why a seeminly extranious bit of code was added. Don't tell me how-- that is what the code is for.

    And use whitespace as your friend to break things up into logical chunks which are easily readable and logically connected. This is the reason for indenting your code, but the same principle can be used by adding additional line breaks to separate logical chunks of code (this makes more sense then meaninglessly breaking up functions).

    I think that these are relatively language independent advice. I use it in Perl and PHP, and when I read C and C++, I appreciate these tips as well.

    --

    LedgerSMB: Open source Accounting/ERP