Slashdot Mirror


Myths About Code Comments

theodp writes "Jason Baker gives his take on the biggest misconceptions about code comments: 1) Comments are free ('When you update the code that the comment references, you usually have to update the comment as well'). 2) Comments make code more readable ('by far the most pervasive myth that I've encountered'). 3) You should comment every function, method, class, and module ('documenting something that needs no documentation is universally a bad idea'). 4) Code must always be 'self documenting' ('would you rather use a one-liner that requires a 3-line comment, or a 10-liner that requires no comments?')."

94 of 580 comments (clear)

  1. One person's myth is another person's fact. by yog · · Score: 5, Insightful

    Well, everyone's welcome to their opinion, but it's pretty well proven after decades of software engineering that code should be commented. The price of maintaining comment-free code is well known.

    There is a school of thought among programmers who consider themselves hotshots that if you are not a hotshot you have no business touching their code. The problem with this attitude is that it has little to do with the real world, where people change jobs and programmers inherit someone else's code. If you want to write perfect, comment free code in your perfect little world, go right ahead, but don't expect to make a living at it most of the time.

    It's surprising to me that someone has submitted this as a "news" item. News flash! Everything you know is wrong. Sorry I don't buy that. If you don't comment your code, I won't pay you for it. I'll inform the management that you neglected an important step and don't deserve a good reference. I won't be able to give you the benefit of the doubt when your code doesn't make perfect sense. I'll trash talk your code in front of your colleagues. Look at all the mistakes in this guy's work; I'll sure never recommend him if his resume crosses my desk. We may need to just rewrite this stuff because it's not maintainable as written.

    What's really annoying is when they put comments that don't elucidate the code or their intent; they're just snide little messages from one know-it-all to another. They're too embarrassed to actually explain the code because that implies a level of insecurity they would rather not admit to. So instead they say things like: /* yeah, I don't like this either */
    or
    # hack, to be fixed later

    Wooooo, really helpful comments there. I've seen this sort of thing countless times in my career and most others I know have as well.

    --
    it's = "it is"; its = possessive. E.g., it's flapping its wings.
    1. Re:One person's myth is another person's fact. by Brian+Gordon · · Score: 3, Insightful

      Woooo, business programming. Believe it or not, there are a few applications out there that require performance and cleverness rather than strict convention. I think that a myth of software development is that every line of code should always be simple and easy to understand. Sometimes things are complicated, especially in performance applications.

    2. Re:One person's myth is another person's fact. by v1 · · Score: 5, Informative

      I find the most important comments are those that tell you WHY something was done the way it was. I do this with my own code when I track down and fix a bug that turns out to be caused by some very subtle effect or easily made mistake. I put the comment there to stop myself (or someone else) from "fixing" / "cleaning it up" later because they don't realize why it's done the way it is. Comments like:

      # yes, 1, not 0. If all four of the lists are allowed to go to 0, we will blow up later with DBZ.

      And having a sometimes very poor memory of code written long ago, this saves me from myself more than others.

      --
      I work for the Department of Redundancy Department.
    3. Re:One person's myth is another person's fact. by MichaelSmith · · Score: 2, Insightful

      I work on a really big hunk of C code and one place I would like to see more comments is in the start and end of blocks. This is because during the life of the code people come in and paste maybe 1000 lines of code from elsewhere into the block and totally stuff up the indenting so its hard to see what is supposed to match to what. This is particularly a problem with importing between branches (my job at the moment) because it can be hard to work out the original intent of the various nested blocks you wind up with.

      Commented out code is a particular problem because my editor can count { and } but it doesn't know if some of those have been commented out, possibly asymmetrically.

      Where I work comments get used to abuse people. You commit a message:
       
      /*Hey $YOU dont do this again */

      But a lot of the comments we have I can't even read because they have been collected by the code in one of the countries it has been to over the last 30 years or so. Many of them seem to be in French and Arabic.

    4. Re:One person's myth is another person's fact. by khallow · · Score: 3, Insightful

      Even the "this is a hack/kludge/abomination unto nature" comments are useful to me. It tells me some starting points for improving the code. Also I write similar comments to remind myself where the iffiest parts of my code are.

    5. Re:One person's myth is another person's fact. by innocent_white_lamb · · Score: 2, Informative

      If you're writing in C, do yourself a favour and check out this editor: http://www.geany.org/

      It's the slickest C editor that I've ever had the pleasure of using. It seems little-known, though, and I don't know why.

      (It handles other stuff than C too, but I haven't used it for any of those yet.)

      --
      If you're a zombie and you know it, bite your friend!
    6. Re:One person's myth is another person's fact. by WED+Fan · · Score: 2, Insightful

      In your race to be first, you failed to read the article.

      --
      Politics is the art of looking for trouble, finding it everywhere, diagnosing it incorrectly and applying the wrong fix.
    7. Re:One person's myth is another person's fact. by 93+Escort+Wagon · · Score: 3, Insightful

      Even the "this is a hack/kludge/abomination unto nature" comments are useful to me. It tells me some starting points for improving the code. Also I write similar comments to remind myself where the iffiest parts of my code are.

      I agree. When I put those sorts of comments in, they are most often notes to myself rather than a legacy left behind for others.

      I prefer to write code that's easily extensible, and in most cases it's what I try to do - but that definitely takes longer than hacking something together (at least for me). Since I'm not the boss, there are times when I've been given direct orders to "just get it done so I can show this to xxxxx, we're never going to need to change this anyway" - and I do it. Down the road I try to fix those when I'm in a slow-ish period; but also, they are valuable reminders when, a year later, the boss comes back and says "can we add yyyyy and zzzzz to that?" because it a) gives me a chance to talk with him about why I prefer writing it right the first time; and b) provides support for telling him why it'll take me a few days to add those features rather than the 1-2 hours he thinks this "minor change" should take.

      On a side note: There's nothing worse than running into someone else's 6-7 year old bit of code containing comments like "hack, important to fix this next revision" - it's too much like finding those silly "under construction" animated gifs on a web page that was last updated in 2003.

      --
      #DeleteChrome
    8. Re:One person's myth is another person's fact. by SteveWoz · · Score: 2, Insightful

      Both the code and the comments should be as understandable as possible. Don't forget that the effort to comment well helps the programmer in his/her own thinking and his/her own understanding of their own code, and helps in development of good code that doesn't have bugs.

      --
      OK a new size TV
    9. Re:One person's myth is another person's fact. by Nutria · · Score: 3, Insightful

      Sure. It's a damned fast way to multiply or divide by a power of 2.

      I'd never do it in a DP shop, though...

      --
      "I don't know, therefore Aliens" Wafflebox1
    10. Re:One person's myth is another person's fact. by Tanuki64 · · Score: 2, Insightful

      I work on a really big hunk of C code and one place I would like to see more comments is in the start and end of blocks. This is because during the life of the code people come in and paste maybe 1000 lines of code from elsewhere into the block and totally stuff up the indenting so its hard to see what is supposed to match to what.

      If the only tool you have is a hammer, every problem looks like a nail. You comments are in this case the nail you desperately want to hammer in, when in reality you need a refactoring. And you need to give the idiot, who pastes the additional 1000 lines, a hearty kick in the ass.

    11. Re:One person's myth is another person's fact. by hedwards · · Score: 2, Insightful

      OK, this topic is officially over. That's the nub of it, if a programmer could intuit what would be confusing a decade down the road or to another developer that takes over, then you can cut out on the comments. The cost of documentation does exist, but people ought to be thinking twice before putting in overly complicated, absolutely must comment code. Sure some cases require that for legitimate reasons, but most of the time you're doing it wrong, and putting in the comment gives you the opportunity to reconsider whether that complex code could be simplified.

    12. Re:One person's myth is another person's fact. by b4dc0d3r · · Score: 2, Interesting

      My opinion is you're a stubborn idiot.

      Allow me to explain. I'd love to see some concrete evidence that commenting is "pretty well proven" as well as a quantified "price of maintaining comment-free code" which you think is "well-known." The very existence of this post, and all of its replies, suggests differently. This has been argued on both sides since the idea of comments first came up. Sure there are commando style morons who refuse to type one comment, just like there were countless commandos who optimized by bypassing the operating system and going directly to the BIOS in the early days. There always will be.

      After decades of software engineering, we moved from spaghetti coded ASM to readable C to object-oriented, class-based programming. Lessons learned early on don't necessarily apply. In fact, the higher level the language, the less documentation seems to be required. If data-hiding is always enforced, there are page after page of code which require absolutely zero comments because they are just get/set methods. The odd "setting this has side effects, which is why we do it this way" is an exception, not the rule.

      The real exception is when you get into complicated event-driven models supported by objects. It's sometimes impossible to tell, looking at your single file where you need to make a change, which object uses this feature, or which event ultimately triggers this method. I've read some of that code, Java being my favorite example, and it's usually very difficult to see where something gets kicked off. Usually I solve it by making a breakpoint and checking the stack trace - but you can't require that someone reading your code have a working dev environment they can just open the code into and start debugging - it has to be understandable while being read, not executed. That stuff needs documentation - but it might be better done in external tech design type docs, not inline.

      Very few programmers are of the hotshot variety - you might be misinterpreting a little. If I build a bridge and someone tears it down and builds a functionally equivalent version, I tend to take it personally. I'm no hotshot and I don't think that person should stay away from my perfect code, but it's something I created being thrown away or altered for no apparent reason. "[I]f you are not a hotshot you have no business touching [my] code" has little to do with the real world because it is rarely seen in the real world. No one gets permanent ownership of a file or block of code, and if you run your ship that way it's your own fault. Set up the environment so that's not even possible. Cross-training someone to be your backup is a relatively common thing to do, and eliminates the possibility of having that hotshot, so if he/she exists, it's management's fault for either enabling or not firing that employee.

      Throwing away code because it's "not maintainable" simply due to lack of comments is laughable. Worse than laughable, it's cryable. Requiring that everything be commented so you can put a check mark in the "my team always comments their code" box makes you sound like the coder's worst nightmare. Creating work for no reason is absurd, but it allows management to claim they are understaffed and need a bigger team. That's the way management promotes itself, seems like - require a bigger team, then use that to show you can handle a bigger team, and it keeps growing because you have people 25% dedicated to commenting code. You're completely missing the point.

      We have had requirements as a result of ISO 9001 and CMM qualification which were just as blind as you are, and as a result have code which does not match the comments at all. The functionality is clear based on context, but in the rush to get a feature out by a client commitment date (that is not within our control) sometimes these things get overlooked. It is far better to reserve comments for when they are needed. And if they are not needed, they should not exist. You want a theoretical team which updates comment

    13. Re:One person's myth is another person's fact. by Nelson · · Score: 3, Insightful

      What did this blog writer actually ever do that's worth a shit? Shouldn't that be one of the first things mentioned? Far as I can tell, he's a nobody that writes a blog. I can't find any references to any important pieces of software he's worked on that makes me think I should give a shit what he thinks. Moreover, the ideas he's propagating are bullshit, what he says is true if you don't write software, don't work on important software, and don't play on teams, otherwise it's just stupidity and he's showing his youth. Nothing to see here, move on.

      Taco, Hemos, Slashdot, et al.., remember way back in the day when we were infested by all those Katz articles and so they implemented the Katz-block technology to let us remove that crap from the front page? I like the developers section but this is a bullshit article, we need to introduce a more fine grained Katz-block. We need an "everything you know is wrong" subsection, a "new language or some shit like that" subsection, and a "technology x is dead" subsection so I can block that crap out of the front page.

    14. Re:One person's myth is another person's fact. by JWSmythe · · Score: 3, Interesting

          I actually did one of those comments a few days ago. There wasn't a better way to do a particular piece of code, so I put the comment in "// This is ugly, but there isn't a better way to do it.". It's a note to myself and future developers not to bother trying to fix an insignificant ugly piece.

          I do agree with the article, not everything needs to be commented. He misses out on "self commenting" where the code explains itself, so you don't need to explain it in an added comment. Intuitive variable names rather than $a $b $c are very helpful both in development, and for future maintaining.

          Sometimes things are overcommented, like the default Apache httpd.conf. I've been known to clean up such files with "mv filename filename.orig | cat filename.orig | grep -v ^# > filename", just to shorten it down to something reasonable that can be read. If you're familiar with the Apache httpd.conf, there's no need for all those comments. But, if someone needs to reference them, they're in the httpd.conf.orig.

      --
      Serious? Seriousness is well above my pay grade.
    15. Re:One person's myth is another person's fact. by DrJimbo · · Score: 2, Funny

      Does it run on Emacs?

      --
      We don't see the world as it is, we see it as we are.
      -- Anais Nin
    16. Re:One person's myth is another person's fact. by Surt · · Score: 2, Insightful

      Most are not hot shots. We have a programming test for applicants to my company. It is really close to trivial. 4 out of 5 applicants for the job of senior software engineer submit a solution so bad they are dismissed immediately. Out of the remaining 20%, only about 1 in 10 submits a solution I consider 'good' (and is therefore a person I consider a possible hot shot candidate). The rest are merely adequate and clearly not hotshot material.

      So that's 2% hotshots at best by my reckoning. Of course, this ignores the fact that our trivial programming problem probably pisses off a few hotshots enough that they don't submit, but we don't want to hire that kind of personality, hotshot or not.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    17. Re:One person's myth is another person's fact. by TheRaven64 · · Score: 2, Informative

      Which is why every compiler for the last 20 years has done it where appropriate. Hell, even the toy compiler I wrote as undergraduate coursework did that transform. All that you achieve by doing it in your code is making your code less readable (and slower on a few architectures and in a few circumstances on others).

      --
      I am TheRaven on Soylent News
    18. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 2, Informative

      Unless you use a really crappy compiler, the compiler will turn a multiplication into a bit-shift for you. That is, unless you're being really clever with bit-shifts, like for example when you write a deeply optimized CRC algorithm which minimizes memory accesses and code size. Very few people write that kind of code though, because it's usually hidden in libraries. Highly optimized (and consequently highly unreadable) code must be highly reusable and should obviously be well documented.

      The "comment your code" dogma is a simplification for people who don't understand that code is written for people as much as it is written for machines. The person reading your code must be able to understand it. If the code alone is clear enough, comments can be harmful (because they pose a risk of code-comment divergence, require maintenance, basically all that was mentioned in the story). The problem is that clever programmers usually have a different idea of "clear enough" than others, so they frequently misjudge the necessity of comments.

      On the other hand, there is this idea that programmers need to change code which they do not fully understand, so there should be plenty comments. That is very dangerous concept which will lead to many problems. If you don't understand the code, do not change it. Too much commenting can lead to overconfidence in maintainers. Comments are human language and therefore imprecise. They provide room for misinterpretations. which in turn increases the chance that the maintainer feels confident that he's fit to change the code even though he is mistaken about the way it works, the circumstances it is used in or other aspects that he should but does not understand. Too little commenting will cause a different kind of maintainer error. If the maintainer does not see a chance of understanding a piece of code, he will either resort to trial and error (feeling confident that test-based programming will do its magic, which it won't) or rip it out completely and rewrite it, but since he doesn't understand the code, the replacement code will fall short of the requirements.

      Clear code which can be understood without comments should not be commented and is really the optimal way of coding. Unfortunately it is also so rare and expensive that "comment your code" as a general rule is still a sane requirement for all levels of programmers. I'm a big fan of high-level documentation, but I rarely see a reason for in-function/in-method comments. They're usually a sign of early optimization (aka unnecessary cleverness, like writing <<1 when you mean *2), bad structure, implicit requirements and other failures which should not be handled at the code-monkey level. If you find yourself writing lots of very local comments, try to find what the actual problem is and solve that, but until you do: Keep commenting your code.

    19. Re:One person's myth is another person's fact. by digitig · · Score: 3, Funny

      Well it is. Sure you lose the LSB but you lose the MSB on multiplication..

      You don't actually lose the MSB -- it shifts into the sign bit. But hey, what harm can that do, eh?

      --
      Quidnam Latine loqui modo coepi?
    20. Re:One person's myth is another person's fact. by GeckoAddict · · Score: 2, Insightful

      This is because during the life of the code people come in and paste maybe 1000 lines of code from elsewhere into the block

      Your design is horribly wrong.

      so its hard to see what is supposed to match to what

      Branches or not, you need a coding standard, fast.

      Where I work comments get used to abuse people.

      Your development team is in need of some management and/or personal communication skills.

    21. Re:One person's myth is another person's fact. by daVinci1980 · · Score: 2, Insightful

      I say this in a slightly different, but more concise way:

      Comments (and self-documenting code) should tell you "what" and "why", because the code is telling you "how".

      --
      I currently have no clever signature witicism to add here.
    22. Re:One person's myth is another person's fact. by honkycat · · Score: 3, Insightful

      My opinion is you're a stubborn idiot.

      Dude, don't be an asshole. Especially when you're about to chastize someone for making assertions and then respond with an even less substantiated steaming pile.

      Comments like "yeah, I don't like this either" or "hack, to be fixed later" indicate your team didn't have enough time to do it the right way the first time. It's a warning to whomever makes changes later that something is amiss. If the coder knew what to comment which might be helpful, they'd probably go ahead and implement it. Perhaps you'd like to see "optimize this" or "I have to stop working on this so I can finish my commenting before peer review so we can meet the deadline."

      No, comments like that are absolutely useless. When you write them, you know the context a lot better than someone who comes in to debug or extend it months or years later. Obviously you recognize there is or may be an inefficiency fragility to the code. Not having time to sort it out is understandable. Not having time to properly note what about the code is fragile or inefficient? Sorry, that's utter bullshit. Take the three minutes necessary to give the reader a proper explanation of what you don't like about it. "This fails if X possible but unlikely condition occurs," "This is unacceptably slow when more than N rows are returned because of Y," or something is more like it. "I don't have time to be helpful" is a lame excuse for not being very good at your job.

      You want a theoretical team which updates comments along with the code, and all peer reviews catch any outstanding comments, your costs are going to skyrocket. The real world requires lots of time to ensure documentation stays up to date, and your focus should be primarily on anything used by external users, second on internal documentation like design or event mapping, and last on code. If you have time and money left.

      Yes. The real world requires documentation be kept up to date. Yes, documentation is part of the cost of coding. It takes more than writing code to built a non-trivial program. What's your point?

      I really don't understand your position. Looking through the blustery hot air you felt it necessary to inject, you seem to understand that comments and documentation are important when necessary. But then you suggest that useless "fixme" comments are ok? And then you say crap like, "Every compiled application out there is completely documented."

      Like you, I'm not a fan of large, boilerplate comments as a rule. However, having reviews that determine whether code is sufficiently commented is quite reasonable. After all, the original programmer is just about the worst person conceivable to determine whether his code needs a comment. Of course it makes sense to him, he just wrote it.

      Looking at your examples of cases when comments are/are not needed, I find it amusing that you suggest an external design doc as being preferable to in-code comments, since the effort and cost of keeping this consistent is orders of magnitude greater than for comments. (I don't necessarily disagree, I just find it discordant with your comment.) Obviously endless get/set methods don't need much in the way of comments. But if that's the bulk of your code, you're not doing much. For non-trivial functions and code, I find it very hard to believe you can get away without most of your functions having a header comment that explains the purpose of the function, or at least the meaning and ranges of the arguments.

      That has no place in the real world, and maybe neither do people like you.

      Nyah nyah nanny-nanny-boo-boo neener neener. Grow up.

    23. Re:One person's myth is another person's fact. by Surt · · Score: 2, Insightful

      Absolutely. Other people, who are not geniuses, will have to maintain the code for years. They must be able to understand it. Someone who is capable of writing something that is incomprehensible to me, and who can't foresee the problems with that is of no value to us.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    24. Re:One person's myth is another person's fact. by Radres · · Score: 2, Insightful

      "Write-only monkeys"? While I think it is expected that a programmer should be able to figure out a given piece of software, even undocumented, given enough time, I think it's a bit severe to expect that any piece of non-trivial software can and should be figured out from raw disassembled code 100% of the time. Just thinking through some of the headaches I've encountered with spaghetti high-level code, I can't imagine trying to decipher that same code at the assembly level, nor how it's a good use of someone's time to have to do so just because someone else couldn't be bothered to comment their code.

      The best technique I've learned is to first write out in English a comment describing what you are about to write in code, then write the code after the comment. If you can't explain what you are going to do in English to begin with, you probably aren't ready to write the code. Doing it this way doesn't cost you that much extra time in the long run, since about 80% of your time as a coder is spent thinking about the problem, and only about 20% is actually writing it up. When done, your code will have a nice natural flow to it, and it will be obvious where you should break out new methods to increase the understanding of the code.

    25. Re:One person's myth is another person's fact. by 12357bd · · Score: 2, Insightful

      The best technique I've learned is to first write out in English a comment describing what you are about to write in code, then write the code after the comment. If you can't explain what you are going to do in English to begin with, you probably aren't ready to write the code.

      I fully agree with the basis of your position. After more than 30 years programming, the way I like to comment my code, is attaching a comment for every instruction. The intention is to explain in plain words what code is doing at every step, and larger and broader ideas on the heads of functions and/or definitions/classes.

      The result is verbose of course, but it can be read linearly, and the underlying algorithm is fully explained. The reader have a plain explanation of the why's and the how's of the code.

      --
      What's in a sig?
    26. Re:One person's myth is another person's fact. by Arthur+Grumbine · · Score: 2, Funny

      Since you have never seen his code and know nothing about its application, it would seem you carry around the "refactor it!" hammer.

      It seems that both of you are carrying around the "with a hammer everything is a nail" analogy hammer.

      --
      Now that I think about it, I'm pretty sure everything I just said is completely wrong.
    27. Re:One person's myth is another person's fact. by Rockoon · · Score: 2, Informative

      Shifting is no longer considered superior to multiplication on x86 because shifting has flag dependencies that multiplication does not have. The P3 was the last processor to favor shifting over multiplication (actually.. not sure about the Atom)

      specifically:

      mul or imul always alters the entire flags register, while shl or sal only alters part of the flags register. This partial update to the flags register breaks out-of-order execution and register renaming (creating a dependency on the state of the flags register prior to the shift), among some other negative effects.

      div and idiv are still dogs and should be avoided.

      For awhile there it was quite difficult to get a C compiler to NOT emit shifts in place of constant multiplications, which became an optimization nightmare for those of us who cared, because the compilers were outright and utterly wrong.

      --
      "His name was James Damore."
    28. Re:One person's myth is another person's fact. by cloudmaster · · Score: 3, Insightful

      To demonstrate why other people might be able to solve a problem you've been stumped by, lets look at the "mv | cat | grep" you provided. :)

      First, that doesn't check the return value of the mv, so if the mv fails, you'll just clobber the original file. And, piping mv is just dirty. The Borne shells provide && for that:

      mv && cat | grep

      So, we have a check that the mv worked before clobbering the original now. This is a good start. But, that removes the original and recreates it - so you're probably mangling the permissions. If you do a cp, you have two gains - you preserve the original permissions of the file, and you guarantee that there will be enough space for the new file (since it'll be smaller or the same size without any comments). So, now we have

      cp && cat | grep

      Finally, the "cat | grep" construct bugs me. Grep takes filenames as arguments; it doesn't have to read stdin. So the cat and pipe is spawning a new process and setting up extra file descriptors which are superfluous. The performance difference is negligible on a one-liner, but if this same construct is used in a tight loop, it adds up. It's basically a bad habit. Just use grep. :) So, ultimately, we have an optimised version which is notably more robust and faster and less to type:

      cp src src.orig && grep -v "^#" src.orig > src

      But wait, there's more! If you're using bash or ksh93, you can use shell word expansion to reduce the chance of typos:

      cp src{,.orig} && grep -v "^#" $_ > src

      And then, say you're sick of all this junk and just want to do it with one command that's shell-independent. Well, lets use perl:

      perl -i.orig -lne 'print unless /^#/' src

      So anyway, don't assume that someone else can't solve a problem more elegantly than you.

      And don't take this post too seriously. ;)

  2. No Comment by Anonymous Coward · · Score: 5, Funny

    No Comment

  3. Cliche, but true... by Xaroth · · Score: 5, Insightful

    Clean code tells you how, good comments tell you why.

    Fixing the "how" becomes significantly easier when you know "why" the code was there in the first place.

    1. Re:Cliche, but true... by Brian+Feldman · · Score: 2, Insightful

      Clean code tells you how, good comments tell you why.

      Fixing the "how" becomes significantly easier when you know "why" the code was there in the first place.

      You seem to be implying here that good comments cannot explain how something non-obvious works. Often in software there are tricky sections of code that benefit from both comments explaining why a given algorithm is implemented but also how the control flow works. Comments are also extremely useful to mark spots that need attention later but are sufficient for now, and also to document any type of "contract" that a particular body of code adheres to.

      --
      Brian Fundakowski Feldman
    2. Re:Cliche, but true... by Wraithlyn · · Score: 3, Insightful

      Indeed, and perhaps it's an obvious point but I'd also add that clean code should also tell you "what".

      Whenever I have a block of code whose purpose seems unclear, I try to put it into a function whose name clearly describes what it does. This immediately makes it more understandable, and reusable to boot.

      Comments should explain why something is done the way it is, the reasoning behind it. They should not simply label what something IS, that should be the job of good naming practices.

      --
      "Mind, as manifested by the capacity to make choices, is to some extent present in every electron." -Freeman Dyson
    3. Re:Cliche, but true... by BikeHelmet · · Score: 3, Interesting

      I don't clutter my code with comments. If there's a comment, it's a really important gotcha, or something that doesn't make sense but has to be left for legacy reasons.

      And I write a detailed description at the top of every file. Not just what a class does, but also why. Why some of the methods do what they do, and other places they might get used that might need to be changed.

      Nothing annoys me more than...

      /* Method name: Foo
      Returns: int Bar
      */
      public int Foo()
      {
      return Bar;
      }

      When a comment could be run through a preprocessor to turn it into the actual code, the comment is saying too much, and should be removed, simplified, or changed.

    4. Re:Cliche, but true... by dkf · · Score: 2, Insightful

      In most high level languages, description method or function names tell you why as well.

      Function (and argument) names don't tell you the why of the function. They tell you why you would call the function. That's an important difference. (For example, a function might be called GenerateUniformRandomNumber(int from, int to), but that does not say anything about the particular algorithm used to do the generation, which might need a few references to the literature on PRNGs to do properly.) If the code has description metadata attached to it then that's quite possibly containing a lot of what is considered by others to be "comment" (even though it's not actually one).

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    5. Re:Cliche, but true... by b4dc0d3r · · Score: 2, Informative

      To supplement my comment elsewhere, what you're suggesting can be more easily documented in a tech design type of document, not inline. It's easier to find that way, and you can include pretty pictures too.

    6. Re:Cliche, but true... by Slackcity · · Score: 2, Insightful

      Right there.

      Intent.

      If I don't see that in comments...

    7. Re:Cliche, but true... by Imagix · · Score: 4, Informative

      You do realize that some of those types of comments aren't really intended for humans anyway, but more for documentation generators like javadoc and doc++ ?

    8. Re:Cliche, but true... by DrKnark · · Score: 2, Insightful

      In certain IDE:s those types of comment are helpful. Mousing over a function call to see what it returns and what the arguments are without having to find the code for that function speeds up coding for me personally at least.

  4. Wrong on all accounts by smartin · · Score: 5, Insightful

    Having worked as a programmer for many years, all I can say is poorly commented and undocumented code is unprofessional and I would rather
    rewrite it than try to decipher it. I've heard all of these excuses before and all I can say to the people that make them is: Your code is not as
    good as you think it is.

    --
    The difference between Canada and the USA is that in Canada healthcare is a right and gun ownership is a privilege.
    1. Re:Wrong on all accounts by CAIMLAS · · Score: 3, Interesting

      What bothers me is not so much undocumented code, but undocumented functions and/or blocks of code. Main should be well documented, and a function should have a line or two explaining its function, but unless its particularly obtuse code, I don't want/need documentation.

      --
      ~/ssh slashdot.org ssh: connect to host slashdot.org port 22: too many beers
    2. Re:Wrong on all accounts by TheRaven64 · · Score: 5, Insightful

      Your code is not as good as you think it is

      Even if it is, the person reading it might not be as good a developer as you, or may be as good (or better) but with different experiences. In both cases, they may not be able to read and understand your good code without comments. When they change it and it breaks as a result, then it's your fault.

      --
      I am TheRaven on Soylent News
    3. Re:Wrong on all accounts by tomhath · · Score: 4, Informative

      Wrong on all accounts

      RTFA, the article starts out with these two sentences:

      It seems to me getting good at writing comments is an under-appreciated part of a Programmer's development. However, I feel that this is a part of programming that's almost as important as writing code itself.

      His point is that worthless comments are worse than no comments at all. Unfortunately a large percentage of the comments you see in code today were autogenerated by the IDE and are just noise.

    4. Re:Wrong on all accounts by SerpentMage · · Score: 2, Interesting

      And therein lies the problem.

      There are two major problems:

      1) As much as I would like to say that documentation helps, I actually don't think it helps unless you writing an API. But even then I wonder. The real problem with documentation is that as much as we would like to keep it up to date, it does not happen. I personally would prefer modular code that works without tricks than code with comments and tricks.

      2) The problem with comments is that it fails the psychological test. When I write something down it does not necessarily mean that another programmer is going to understand what I mean. The reason has to do with the words I choose and how I phrase things. Even with good wording I can't explain a complex system. For example, let's say that I had to explain some complex multi-threading code. Unless the third party had a level of knowledge as good as mine it will not matter what I write as a comment since they lack the basic threading knowledge. And this lack knowledge is a key problem in any complex system.

      Thus if I had to choose between comments and simplicity I choose simplicity since one can understand simplicity.

      --

      "You can't make a race horse of a pig"
      "No," said Samuel, "but you can make very fast pig"
    5. Re:Wrong on all accounts by Nerdfest · · Score: 2, Insightful

      You shouldn't need to decipher the code. Most of the problem is not the missing documentation, but the poorly written code.

    6. Re:Wrong on all accounts by Nerdfest · · Score: 3, Interesting

      .. and also, you are correct. With code that needs to be deciphered, you're generally better off re-writing it.

    7. Re:Wrong on all accounts by jbolden · · Score: 2, Insightful

      The next programmer in line may not need to understand the complex multi threaded stuff at all. For example he may be revising the UI or the backend datastore. Reading your multi threaded comment may be effectively him just having a comment that the is no I/O and that the block is all CPU / memory; and that is good enough.

    8. Re:Wrong on all accounts by 0xdeadbeef · · Score: 3, Insightful

      If you have to "decipher" code, it is wasn't good to begin with. I used to believe the comment religion, it was beat into us in school, but once I started working with people with similar or greater skill than mine, I noticed that comments became few and far between. Usually they are only necessary to explain the intersection with something external or poorly designed, such as an API call or hackish work-around. Comments are no substitute for not knowing the problem domain. If you need to educate a new hire, you should already have documentation that explains the architecture.

      If you want to talk unprofessional, the absolute worst are comments that state the obvious. It's like watching a movie with an imbecile talking to the screen, telling himself everything that is happening. It goes without saying that those comments are usually uncapitalized, lacking punctuation, and full of misspellings.

  5. Re:Over documentation is good by fdrebin · · Score: 5, Interesting

    Remember what is crystal clear to you may not be to the guy coming in to clean your mess up in a few years. ( or even yourself as you have learned more and advanced your skills, and have to go back, often with a 'wtf was i doing'.. )

    I worked on the same system for 15 years. More than once I saw some code and said "what idiot wrote this!?" ... only to realize it was me, 5 years ago. Yes, that did indeed lead to me becoming a) much less prone to "clever tricks" and b) much much better at explaining what (WHY) I was doing whatever it was.

    --
    Stupidity... has a habit of getting its way.
  6. Has No One Actually Studied This? by Greg+Hullender · · Score: 4, Insightful
    In thirty years of programming, I've heard one person after another argue about how to comment and how much to comment, but what I've never seen is any kind of serious study attempting to measure what actually works best. I personally like to make comments paragraphs, not lines, and generally end up with code that's 1/3 to 1/2 comment lines, but the most I can claim is "it works for me."

    I do think good commenting has to be a key part of software engineering (when it finally becomes a real engineering discipline), and I know software engineering is a hot topic these days, so perhaps there's a paper on this that I just haven't seen yet. If not, someone really ought to do a serious study. And then start teaching people something that's actually known to work.

    --Greg

    1. Re:Has No One Actually Studied This? by tomhath · · Score: 5, Insightful

      A former employer (a very big multinational corporation) did a study that tried to correlate the number of comments in code to the number of problem reports against it. Not surprising to me, they found that in general the more comments in the code, the more problems were reported against it. That was my observation as well; bad programmers couldn't figure out a straightforward solution to a problem so they wrote messy code with lots of comments trying to explain what they were doing. The really good programmers wrote simple clean code that only needed a few comments.

      Another characteristic of bad programmers that I noticed was their tendency to keep copying data from one data structure to another instead of using it in place. Obviously an indication of bad design, and it introduced lots of bugs. You knew as soon as you opened a source file and saw comments like "Copy blah-blah data from abc array to xyz array" that you were in trouble.

    2. Re:Has No One Actually Studied This? by jim_v2000 · · Score: 2, Funny

      > they found that in general the more comments in the code, the more problems were reported against i

      The obvious solution then is to simply ban employees from using comments in code.

      --
      Don't take life so seriously. No one makes it out alive.
    3. Re:Has No One Actually Studied This? by digitig · · Score: 2, Interesting

      A former employer (a very big multinational corporation) did a study that tried to correlate the number of comments in code to the number of problem reports against it.

      Which seems to me to be representative of the sort of blunder very big multinational corporations seem particularly prone to. Just count the comments, never mind what the comment says. /* Stable sort in place, efficiency O(n log n) */ counts for the same as /* Oblig comment coz a dude in QA sez I has to */

      --
      Quidnam Latine loqui modo coepi?
    4. Re:Has No One Actually Studied This? by Byzantine · · Score: 2, Informative

      Sounds sorta like literate programming.

    5. Re:Has No One Actually Studied This? by adamrut · · Score: 2, Interesting

      If not, someone really ought to do a serious study. And then start teaching people something that's actually known to work.

      I'd be interested to see a study, but I'm sure it'd create more questions than answers given how hotly every side of this argument is debated. I think that writing good comments is much like writing good code, the only way you get good at it is reading, writing and re-writing lots and lots of code/comments. After a while you know what needs to be commented, the way it needs to be commented and you know what doesn't need to be commented. Writing relevant information clearly and concisely is a skill that must be learned and practiced.

    6. Re:Has No One Actually Studied This? by JetTredmont · · Score: 2, Insightful

      It's funny, a lot of the examples you see on MSDN and similar are often not very commented. I'm not saying this always produces readable code, but as the examples are "at the correct level", it tends to be quite readable.

      There are three factors at play there. First, more comments means more lines of code, which makes a "simple" example seem larger. Second, it's a lot easier to explain how an example works in the text surrounding that example (in the overview document for MSDN, or in the non-code portion of a tutorial, etc). Long-form text is much easier to read with a proportional font and paragraph structure. Also, it's often NOT the original developer of the code entrusted to writing the documentation. Third, and importantly, these are generally relatively trivial pieces of code.

      From my personal experience, such snippets of code tend to be pulled from larger works, and have a "simplification" process where both any hooks to the rest of the system are simplified (preferably entirely away) and all comments are removed (the tech writer working the tutorial might preserve these comments to make sure they cover the bases in the tutorial/etc). As such, it's no accident or coincidence that they have few if any comments left once published. It doesn't necessarily indicate that the original code was comment free (although that may have been the case).

      In one system where I work there are hundreds of pages on deployment procedures. In ours we managed to automate 99% of the process. Which would you rather have?

      I'd rather have the procedures automated with well-commented code. Because no matter how well your code is structured, the realm outside (the process that your deployment process fits into) is not so neatly structured.

      I don't see how arguing for/against intellisense fits in here. I love to use intellisense (er, well, the non-Microsoft trademarked variety), AND I love to have comments in code I am scanning when looking for a bug or a way to fit a new needed feature in.

    7. Re:Has No One Actually Studied This? by digitig · · Score: 2, Insightful

      Yes, but the reason CS students talk about sort algorithms is that they're a convenient didactic example that everybody can understand. If I'd taken an example from the actual stuff I've worked on, most people wouldn't know what I was talking about.

      --
      Quidnam Latine loqui modo coepi?
  7. More verbose == less readable? by nmb3000 · · Score: 4, Insightful

    I disagree with this general statement:

    For instance, would you rather use a one-liner that requires a 3-line comment, or a 10-liner that requires no comments? In most cases, code's readability suffers more when it's overly verbose than when it has a high comment to code ratio. Thus, I would choose to write the comment in most cases.

    First, I think any time you consider writing some clever one-liner in real production code you should rethink long and hard. Is the hypothetical 6 fewer lines of code really worth it? Unless you're doing it for absolutely required performance reasons, the 6 lines of code you save won't buy you anything but the wrath of whoever has to come along in 3 years and refactor your code.

    Of course you can be too verbose, but it's a much rarer problem than the alternative. Even overly verbose code is usually easier to understand, easier to maintain, and easier to refactor than that clever little one-liner. And if you're that worried about a verbose section of code, extract a method, give it a good name, and be done. Now you have both a one-liner method call that is easy to read in context and a more verbose implementation that is easier to understand and maintain in the future.

    --
    "What do you despise? By this are you truly known." --Princess Irulan, Manual of Muad'Dib
    /)
  8. In other news... by CAIMLAS · · Score: 4, Insightful

    In other news, people have personal preferences, just as they do in the literary world. Some people like Ayn Rand, others hate her. Some like Stephen King, others hate him. Not so much their stories, but their writing styles.

    Snowcrash is an awesome story; one many can appreciate, but most people couldn't get through his writing style to finish the book.

    I think that if more people wrote code (or, for that matter, books) like George Orwell wrote his books, code (and books) would be generally more readable: shorter sentences (lines of code) which convey a single meaning (function), strung together into short paragraphs (code blocks), chained together into a larger cohesive whole.

    --
    ~/ssh slashdot.org ssh: connect to host slashdot.org port 22: too many beers
  9. Please no by dachshund · · Score: 5, Insightful

    Christ, I know everyone has their own personal style and everything, but this is just pernicious. In any case, the author gives the game away: when he thinks code is overcommented, he can ask Emacs to hide the comments. So far as I know there's no automatic system that will generate the comments that the author failed to put in because the code was "self-documenting". This is particularly important when you're working with anything other than standard libraries --- you might know what "libfzp_inc_param_count_fast", but your reader probably won't.

    Right now I'm working on a crypto library that incorporates a lot of very specific elliptic curve operations. My technique is to comment the hell out of every damned interesting piece of code on the assumption that a picky reader can turn off the damned comments if they get in his way. In fact, there are various places where I've actually scaffolded all of the comments before writing a line of code. Doing otherwise would have been an enormous headache and made bugs a whole lot more likely. And this way even a non-expert should be able to understand the entire program flow.

    Unfortunately, one of the previous pieces of software in this area followed the poster's "self documenting code" style (very nice, clean, well written code with no comments), and even I find it difficult to piece together what's going on in places --- not because all of the code is crypto-specific, but because the author has thrown so much effort into writing "clean, pretty" code that it's actually hard to know where the crucial pieces are. I can't quite explain why I find this so irritating, but perhaps some of you will know what I mean.

  10. Choice of Language by mandelbr0t · · Score: 2, Insightful

    It really depends on what language you write your code in. Object-oriented languages in general require less documentation since good design and properly named methods and properties do document things relatively well. Class-level documentation is much more important than documenting the details of the methods themselves. Java and .NET require much less documentation to maintain. I've looked over Java code I wrote years ago, and it still makes perfect sense, even though I've only really documented the API and not the details. Perl and C code, on the other hand, can be unmaintainable even with a number of comments, because the old functional design is not easily maintainable. Consider rewriting these in a more modern language.

    Call me a hotshot if you want, but I shouldn't have to assume that the person maintaining my code is a moron, nor that my non-technical manager needs to understand every single statement I wrote. I play nice with QA, and happily write test cases for my code. That's as far as I'm willing to go to ensure that my code quality is good, and that I can leave without the possibility of my code degenerating into the spaghetti-like mess I've had to clean up on a number of occasions. Sure, I don't get hired to write code anymore, but I don't care. Software Engineering and overdocumenting every single tiny intranet project is wasteful. Cleaning up after morons who believe that their engineering background can make up for their lack of talent and experience is aggravating. Answering to them is intolerable. There's other things I can do with my technical background that don't involve butting heads with people who dogmatically apply software engineering methodology to everything they do. It's their loss, not mine.

    --
    "Please describe the scientific nature of the 'whammy'" - Agent Scully
  11. Does he think comments are pseudocode? by EsJay · · Score: 4, Informative

    When you update the code that the comment references, you usually have to update the comment as well.

    If your comments are that detailed, you're doing it wrong.

    1. Re:Does he think comments are pseudocode? by presidenteloco · · Score: 2, Interesting

      Except that a programmer should be able to use (call) your api / public methods without having to read their
      implementation. The method signature and comments should be enough.

      Therefore, as well as conveying the gist of what the thing/method is and how it fits into its context,
      you should also document all significant corner cases or unexpected behaviours of your object/method.

      And if you change the implementation in such a way that you falsify one of those comments, without
      modifying the comment, thats a fail, and renders your code library low quality in one stroke.

      --

      Where are we going and why are we in a handbasket?
  12. So who is this guy? by anti-NAT · · Score: 5, Insightful

    No offence intended to him, but he's just re-interating the sort of commentary on commenting that's in Code Complete, The Practice of Programming, Linux kernel CodingStyle etc. He's not offering any original insights, or telling war stories that people can learn from. Any decent programmer would already know these myths, and if they didn't, they really should be reading books such as the ones I've listed, not a blog entry with very little original content.

    IOW, what makes special enough to be Slashdot front page news?

    --
    The Internet's nature is peer to peer - 20050301_cs_profs.pdf
    1. Re:So who is this guy? by Sapphon · · Score: 2, Funny

      It's New Year's Day. What did you want – "Y2K bug still not here"?

      --
      Antiquis temporibus, nati tibi similes in rupibus ventosissimis exponebantur ad necem.
  13. "would you rather use a one-liner" by lax-goalie · · Score: 4, Insightful

    would you rather use a one-liner that requires a 3-line comment, or a 10-liner that requires no comments?

    Easy. 10 lines, no comments. After writing a couple of million lines of code, the more code I write, the more I unwind it. Somewhere along the line, adolescent programmers got the idea that jamming all your logic into as few unreadable lines as possible is the fastest way to manliness. Way, way wrong.

    Modern compilers and interpreters do a pretty good job nowadays. Source code bytes are near free. If you have to skull out dense code 6 months after you've written it, you're doing something wrong.

    (OK, Lisp and APL are special cases, but really, when's the last time you wrote Lisp or APL, other than for fun?)

  14. every line of code should be commented by caywen · · Score: 5, Funny

    Every line should be commented, like: // Declare function called doit with one int param that returns an int
    int doit(int i) // See above comment
    { // The function's open brace. I like to put braces on their own line. You should too!! BTW, this is C code, so braces are totally the way to go.
          if(i == 0) // Check if i is 0. You know, in C, "==" is the way to compare values, unlike in VB where you use a single "=". Just thought u should know.
                return 0; // Return 0. That is, all the bits of the return value are 0. We could also return i, because i is 0, too. That is, all the bits of i are 0. On a 32 bit system, there would be, like, 32 0's.
          else
          { // Begin an if block using a brace (this is C syntax!!!)
                int j = i - 1; // Declare an int variable named j that is one less than i
                return i + doit(j); // Return the sum of i and the value of calling doit with j
          } // Finish the if block with a C close brace. By the way, we could have written the above code as return i + doit(i - 1) without using the braces.
    } // The function's close brace.

    There! Now that is both way readable and informative. Anything less would just not pass my code review.

  15. You made his argument for him by dreamchaser · · Score: 2, Insightful

    Woooo, business programming. Believe it or not, there are a few applications out there that require performance and cleverness rather than strict convention. I think that a myth of software development is that every line of code should always be simple and easy to understand. Sometimes things are complicated, especially in performance applications

    GP never said that (re:bolded text), and the point you are trying to make makes a strong argument FOR clear, concise comments on code. Good code isn't always easy to read at first glance and appropriate comments are important in any project with more than one programmer.

    1. Re:You made his argument for him by DG · · Score: 4, Insightful

      Indeed.

      Sometimes there is a very good reason for including clever, non-intuitive code in a project. But that clever code needs to be very well documented because the next guy to touch it may not be that clever.

      When in doubt, optimize code for future maintainability and legibility. Hardware gets faster. Programmers don't.

      DG

      --
      Want to learn about race cars? Read my Book
    2. Re:You made his argument for him by pz · · Score: 3, Insightful

      I can't count the number of times I've written a very carefully researched small handful of lines of code that are either not intuitively obvious, or would leave more questions than they answered when read. When I've spent days demonstrating through thorough measurement that, for example, a certain constant requires a specific value, that fact gets documented with potentially many paragraphs of comments. Not doing so would be irresponsible, and a waste of my time when I tried to understand, months or years hence, why I had written that small handful of lines.

      To quote one of the Ramones who was criticized in an interview for writing songs with only three chords, "yeah, but they're the RIGHT three chords." With music you can feel if the chords are right. With code, sometimes you have to document.

      --

      Put my fist through my alarm clock with its ding-dong death inside my ear. - The Blackjacks.
  16. Not commenting is a sign of not thinking or caring by presidenteloco · · Score: 3, Insightful

    If you don't header-comment your class or public method,
    I have to conclude that you cannot articulate what it is or what it
    means or is for. So probably the code is incoherent/inconsistent too.

    So that's going to make me write my own instead of using your code.

    Or maybe you can articulate what it is about but are borderline
    autistic and don't see the need to communicate meaning to others.
    To me this just means you are so inexperienced in programming that
    you a) don't understand the costs of maintenance, and
    b) don't even realize that you yourself aren't going to be able to figure
    out your code in six months.
    Either way, I'm not using that code if I can help it.

    --

    Where are we going and why are we in a handbasket?
  17. Re:Over documentation is good by jocabergs · · Score: 2, Insightful

    I think over documentation isn't on the whole a bad thing, but there have been a few times where I've been more confused by the comments than the code. I don't care if people get clever with code and have clear comments, but I hate when people try to have clever comments, comments are not supposed to be hard to understand.

  18. Strongly RESTRICT Code Commenting by omb · · Score: 2, Insightful

    There are just 3 good reasons for comments in code: (a) to refer to a published paper describing an (obscure) algorithm, eg '[fast graph traversal algorithm, M. M. Balakrishnarajan and P. Venuvanalingam ,Computers & Chemistry, Volume 19, Issue 2, June 1995, Pages 101-106] , (b) to indicate an arcane, obscure usage, which would be better eliminated, but sometimes cannot be eg in device drivers, when merely addressing a device register has side effects, (c) to very briefly document major parts of program flow-meaning, if this isn't otherwise obvious.

    In addition, temporary development comments help while writing or refactoring code, but they come out and become empty or (a)-(c), eg // XXXX I dont understand this; or # Class is defined in Foo.pm.

    Usually code is OVER commented, or the comments are facile eg 'i++; // increment i' and this CRAP should be avoided at all costs.

    The other thing to be avoided is lengthy legalese or copyright information spread all over code. If this is necessary, at all, it should fit on one line and if necessary reference a COPYRIGHT or LEGAL file

    OK // Copyright (c) 2001-2010 Foo.Bar, all rights reserved, Licenced under the MIT license.

    BAD /* Error constants. Linux specific version.

    -- 15 lines deleted

          02111-1307 USA. */

    Finally, never believe the comments, at minimum they didnt get debugged!

  19. Less verbose is more writeable by Anonymous Coward · · Score: 3, Insightful

    Early COBOL and Fortran computation code proves you wrong here. COBOL, without COMPUTE, required a separate line for each operation. Fortran from the start showed simple algebraic equations.

    COBOL
    ======
    MULTIPLY B BY B GIVING B-SQUARED.
    MULTIPLY A BY C GIVING A-C.
    MULTIPLY A-C BY 4 GIVING A-C-4.
    MULTIPLY A BY 2 GIVING A-2.
    SUBTRACT A-C-4 FROM B-SQUARED GIVING DISCR.
    CALL SQRT USING DISCR GIVING RT-DISCR.
    SUBTRACT B FROM RT-DISCR.
    DIVIDE RT-DISCR BY A-2 GIVING ROOT-1.

    Fortran
    =====
    R1 = (-B + SQRT(B**2 - 4*A*C))/(2*A)

    Do you want 8 lines of code to write out the quadradic formula? Is that any clearer than one line? A simple one-line comment explains what *root-1* means to the program as a whole.

    I've seen people write out intermediate variables like that using PHP or Python. Both languages handle that for you.

    1. Re:Less verbose is more writeable by Ragzouken · · Score: 4, Interesting

      Your example misses the point precisely because it's just as clear in one line than in eight. You obviously shouldn't break up everything into as many lines as possible.

    2. Re:Less verbose is more writeable by zippthorne · · Score: 2, Insightful

      Either way you need commments. Your example code only finds one root, and doesn't handle the case of positive b and abs(ac/b^2) 1 very well. Your comments could explain why you don't expect that case to arise, and why you only need one root.

      --
      Can you be Even More Awesome?!
  20. Commenting "why" by Chris+Newton · · Score: 2, Informative

    I've heard one person after another argue about how to comment and how much to comment, but what I've never seen is any kind of serious study attempting to measure what actually works best.

    FWIW, in studies of the problems developers encounter in practice, one recurring difficulty is working out the motivation behind a given piece of code. This supports advice to comment why the code is written the way it is. See, for example:

    • LaToza, Thomas D., et al, Maintaining Mental Models: A Study of Developer Work Habits, in ICSE '06: Proceedings of the 28th international conference on Software Engineering
    • Ko, Andrew J., et al, Information Needs in Collocated Software Development Teams, in ICSE '07: Proceedings of the 29th international conference on Software Engineering

    Both papers were coauthored by Robert DeLine and Gina Venolia of Microsoft Research.

    In LaToza, 66% agreed that "understanding the rationale behind a piece of code" was a serious problem for them.

    In Ko, "Why was the code implemented this way?" was the second most frequently unsatisfied information need among the developers observed.

  21. Or by MichaelSmith · · Score: 3, Insightful

    The code which is business critical and necessarily complex gets commented a lot as a mitigation measure. But it still has problems, often because the business requirements change a lot or are poorly defined.

  22. compares to all professions by DaveGod · · Score: 4, Insightful

    Working in accountancy (and doubly-so for audit) a well-commented file is absolutely necessary. Like (I suspect) computer code, the file should stand on it's own - a competent fellow professional should be able to fully understand it and be comfortable reaching the same conclusions. This is not only good practice for the benefit of your firm but a professional requirement: my institute comes along every few years, selects a few files and basically if they have difficulty understanding the file (or worse, reached different conclusions) then you're in a lot of trouble.

    Many of the points in TFA hold up well however - explaining things unnecessarily merely adds bloat, irritates and wastes the time of the reader by telling them obvious, patronising or pointless things. And yes, a perfect accounts job doesn't require any explanation because the schedules will be self-explanatory.

    The thing is though, if you're doing anything complex (earning your salary), have to make corrections (hackjobs) or judgements then you need explanations. Manager's will be reviewing your work and you or a colleague will be referring to it next year. If explanations go out of date, update them - if they had value before then value is there in updating them. Yes there is a cost, so there is a tradeoff vs their value to the file. The key is competent fellow professional. Assume your colleague will be reviewing your work and be satisfied that they will be able to understand and appreciate it.

    If you're just churning out "stuff that works" then you're at best a technician.

  23. The flipside by BigBadBus · · Score: 2, Interesting

    I used to work for a company that didn't believe in commenting code...took ages to reverse engineer the code...

  24. Where is your proof? by SuperKendall · · Score: 2, Insightful

    Well, everyone's welcome to their opinion, but it's pretty well proven after decades of software engineering that code should be commented.

    From my decades of software experience across several different languages, there is no such clarity.

    Comments are useful, but code is often clear enough by itself. And bad (out of date) comments are absolutely worse than no comments at all as a coder will often trust the comments first.

    So while some code should be commented, not all code should be. And that's not really opinion but carefully measured analysis.

    If you don't comment your code, I won't pay you for it. I'll inform the management that you neglected an important step and don't deserve a good reference.

    Well that's not in the least psychotic.

    I comment my code carefully when it needs it, but you are the last person on the planet I would want to work for in case I accidentally cross the invisible line that triggers your Code Rage, and certainly from past experience I know it's bad news to work for people who value procedure about quality and productivity.

    --
    "There is more worth loving than we have strength to love." - Brian Jay Stanley
  25. Experience by GrahamCox · · Score: 2, Interesting

    Experience shows how much you need to comment and what the comments worth writing consist of, just as experience tells you how to structure the code in the first place. "Rules" about commenting are perhaps useful starting points for the inexperienced, but with experience you can write your own rules.

  26. Kernighan by HiggsBison · · Score: 4, Informative

    It was Brian Kernighan who pointed out that:
    "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

    --
    My other car is a 1984 Nark Avenger.
    1. Re:Kernighan by zill · · Score: 4, Funny

      So I should dumb myself down with a hammer before writing code?

      I'm not sure how I'd reverse the process before debugging though. Maybe I should have thought of that before the hammer came down...

    2. Re:Kernighan by DLG · · Score: 2, Insightful

      This is a point I really am trying to make too... The best code you do, the stuff that required you to actually use your brain hard, is going to be hard for YOU to maintain let alone others. You comment based on your own Eureka moments, you document your understanding, and hopefully it lets a person recognize that you were both solving the problem in a reasonable manner, and that your implementation and solution are in sync.

      Beyond that, adding a few lines of code for clarity can also make it easier to debug, to extend and to implement in a different language.

    3. Re:Kernighan by Anon+E.+Muss · · Score: 3, Funny

      So I should dumb myself down with a hammer before writing code?

      You can do it that way, but I prefer whiskey.

      (Obligitory XKCD reference)

      --
      The key sequence to access my Slashdot bookmark in Firefox is Alt-B-S. I don't believe this is a coincidence.
    4. Re:Kernighan by TheLink · · Score: 2, Interesting

      But it's a fact that most people are not always at their smartest all the time. And those that are at their smartest all the time, aren't usually smart.

      So when you write really clever code when you are one of your peak points, you better be smart enough to explain it to your dumb self some time later when some thing needs to be changed (even if it isn't actually affected, you might not remember or understand anymore the reasons that it isn't affected ;) ).

      --
    5. Re:Kernighan by azgard · · Score: 2, Insightful

      Thank you, you finally helped me to understand that comic. So it's true after all. You code while intoxicated, and debug sober, when you are smart enough to easily debug your own code. That way you save debugging time, and you get more productive.

  27. Most of what you say is wrong by petes_PoV · · Score: 3, Insightful
    You presume that the person coming after you will have both your background and your programming ability. This is incorrect. No-one who sees your code will have the same background you have and therefore they will not have the same writing style or familiarity with the problem you were trying to solve. Comments are primarily (but see later) there to save time. They act like signposts on the roadside and should guide people towards an understanding of what a section of code does, why it does it and how it relates to the stuff around it. If your comments don't do this, then you're not a very good programmer. Just like you can drive around and will eventually (as the earth is round) wind up at your destination, having a map, signage and/or a GPS makes getting to the right place a whole lot quicker. Your comments should do the same.

    While you are right (as all *experienced* programmers know, anyway) that /* increment the counter */ comments are pointless (but harmless) you've missed an extremely significant type of comments. These are the warning to future programmers why you DIDN'T use the obvious approach, or why a particular algorithm is not suitable for the task in question. Further, code that has been corrected, modified or had bugs fixed MUST have comments to identify that fact. These comments are at least as valuable as the actual code. Again, experience will teach you this.

    Finally, never, ever forget the most important rule of commenting. NEVER include a URL in a comment. They change over time and cannot be relied upon to still exist in 3 months, let alone the lifetime of a software product. A similar warning should exist for book / magazine references, too. Not only do they become unobtainable or go out of print, they also get modified or corrected in the "second edition" and therefore still can't be relied on. If an algorithm has a well known name, such as Bresenham's, then by all means quote that otherwise, explain the algorithm in, or before the code that implements it. Unless you want the next guy to curse your name - provided you put that in the comments.

    --
    politicians are like babies' nappies: they should both be changed regularly and for the same reasons
  28. Warning - war story ahead by tengwar · · Score: 4, Funny
    My favourite bit of code was about 22 years ago. It was supposed to control some scientific equipment that we had bought from Denmark, and I had insisted on getting the source because of previous problems with the supplier. In summary:

    - 6000 lines of Pascal
    - 200 global variables
    - 3 local variables
    - 1 comment - the single word "midlertidig"

    Oh, and one bug. Code really was less buggy back then.

    Now get off my lawn, you kids.

  29. Comments are useful by trbarry · · Score: 2, Insightful

    There is another myth that says just because something is mathematically unambiguous it also intuitively obvious. And yet the real implications may be lost in the complexity of the situation or problem. Comments can point out anything useful to the code reader.

    Also, if you spend enough time staring at a piece of code you can usually figure out what it does. But that does not at all mean you can figure out what the programmer was really trying to do. His/her internt may have been quite different. You can also not figure out all the possibly erroneous assumptions made about the problem space at the time of coding.

    Comments form a useful redundancy and sanity check. Being cutely terse in comments is as bad as the clever but incomprehensible code one liner.

    You should add comments anywhere you can predict a reader may have a high probability of misunderstanding.

    - Tom

  30. Re:Code format by Ash+Vince · · Score: 2, Informative

    An 80 column line limit is also OLD, I never edit in narrow windows >160 common.

    How you edit is not important, how the team you are part of all edit is. By making lines 160 characters long you force everyone to have to code the same way you do. What is lost to you by breaking a line at 80 characters since it is much easier to scroll up and down in a document than it is to have to scroll left and right once a line.

    This the single worst trait found in developers, (I know I suffer from it) a lack of consideration for being part of a team.

    --
    I dont read /. to RTFA, I read /. to offend people in ignorance.
  31. How does this even deserve a /. ? by upuv · · Score: 2, Insightful

    Because his opinion is against a fairly standard convention he declares himself right and the opposite opinion to be myth.

    How arrogant can you get. Really.

    "I think MS Windows sucks Donkey Nuggets. Therefore everyone should switch to Android. The power I wield is frightening."

    I've been writing code for over 20 years. One thing you learn is that you don't want those "Hey how do you do xyz with method ABC in the code you wrote 10 years ago." calls. How do you avoid this your code follows you like a bad poo cling on. YOU COMMENT YOUR CODE. With descriptions, examples, purpose and anything else that is relevant. You probably should spend as much if not more time on the comments than the code. Cause it will save you heaps of time in the future.

    As for documentation that is external to the code? Well it's useless. Because repositories change move and mutate. Over the years the design/requirements/arch docs all seem to vanish. The only thing that seems to live on is the actual code. Why. The code is the business not the power point slide show. The code therefore should also be the documentation.

    So Mr. I'm 20something and know everything about writing code. Time to join the real world. I for one never want to have to fix your code.

  32. Re:Code format by bingoUV · · Score: 3, Insightful

    Citations:
    http://desktoppub.about.com/cs/finetypography/ht/line_length.htm
    http://desktoppub.about.com/library/nosearch/bl-linelength.htm

    Notice how newspapers break the content into columns, even if a single article covers 5 columns in page width? There is an optimal text width that helps people read best. 80 might be a number coming from punch card days, but it is still a good approximation of "ideal" column width as used by various publishing standards. It is, in fact, a bit more than ideal column width. I see 2 reasons for this:

    1. Breaking simple text simply results in excessive hyphenation. Breaking code into multiple lines has higher impact because code has its own indentation too.
    2. Indented code that starts at 20th column and ends in 80th column => total width is 60 columns which closer to the ideal columns width.

    --
    Bingo Dictionary - Pragmatist, n. A myopic idealist.