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?')."

580 comments

  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 Anonymous Coward · · Score: 0

      Bit-shifting as multiplication?!

      Mind == blown.

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

    6. Re:One person's myth is another person's fact. by TheRaven64 · · Score: 1

      It's possible to write code that doesn't need any comments. Code where the next person to read it will understand exactly what it does and why, just from the code. The difficult thing is knowing when you've done this and when you've written something confusing. If you can tell the two apart with 100% accuracy, then you can skip writing comments.

      Unfortunately, I've never met a developer that could. I've met quite a few that thought they could, however...

      --
      I am TheRaven on Soylent News
    7. 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!
    8. 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.
    9. 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
    10. Re:One person's myth is another person's fact. by SanityInAnarchy · · Score: 1, Insightful

      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.

      I don't see anyone claiming that here.

      If you want to write perfect, comment free code in your perfect little world, go right ahead,

      Nor that. At least Read The Fine Summary (attempting to increase my character-per-line count to avoid lameness filter):

      documenting something that needs no documentation is universally a bad idea

      And from The Fine Article:

      Comments don't make code more readable. They are ways to compensate for code not being readable.

      Which does happen. Again, from The Fine Summary:

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

      But probably the biggest thing you missed is right at the top of The Fine Article:

      It seems to me getting good at writing comments is an under-appreciated part of a Programmer's development.

      I actually agree with most of what you said, but I would fix this for you:

      If you don't document your code, I won't pay you for it.

      Self-documenting code is a reality. It does work. And if you're going to carry out all your threats simply because I didn't do this:

      // Gets the id
      public int getId() {
      return id;
      }
      // Sets the id
      public int setId() {
      return id;
      }

      In that case, yeah, it sucks that I don't get a reference, but I'd be glad to be unemployed again, looking for a job where I can do this instead:

      attr_accessor :id

      Part of the reason I suspect you have a problem:

      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.

      You seem to have a healthy dose of envy and disdain for the people who work under you. You're also missing the point:

      /* yeah, I don't like this either */
      # hack, to be fixed later

      The first is a potential problem, but a little humor from one developer to another... Sometimes the code is a mess, and no amount of comments will help that. The best you could hope for is "I don't like this, and here's why:", or "This is how it works... I know, I don't like it either."

      But that second comment, "hack, to be fixed later"? You should institutionalize that, because it is, in fact, a good practice. Make them do this:

      TODO: fix this hack later.

      Then have your CI system automagically create tickets for that -- they are indeed bugs, and should be fixed. But they aren't just bugs in documentation -- you should be removing hacks in the first place.

      But if your developers feel they have to write a quick hack instead of Doing It Right, it's probably not their fault, it's your fault as a manager for setting unreasonable deadlines. Requiring them to thoroughly document their hacks isn't going to improve things, it's going to take time away from real work, resulting in less good code, and more hacks -- maybe ultimately reducing your program to a single 300 character long regular expression, but man, is it well-commented!

      And you are again missing the point. The point is not that we are hotshot programmers who don't think non-hotshots should be messing with our code. Rather, we are competent professionals who expect people to understand the basics of the language before reading our code, and even then...

      class Story
      has_many :comments
      belongs_to

      --
      Don't thank God, thank a doctor!
    11. 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
    12. 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
    13. Re:One person's myth is another person's fact. by buddyglass · · Score: 1

      IMO it boils down to "if it's complicated then comment it, otherwise don't". Unnecessary comments just get in the way. I'd add that lots of code is complicated and "hairy", and thus deserves comments, solely because its author was not skilled enough to create a cleaner solution.

    14. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      If this concept is hard for you, you're in a wrong business. Get out while you can.

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

    16. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      Yes. Many programmers (most, I would wager) are not hot shots. Many of them may think they are, but they're not. Maybe the percentage of "meh" is even 99%; who knows.

      But surely you do not believe that EVERY person is mediocre. The problem I have with the view you have presented (and I mean nothing personal by this) is that you've essentially mandated that everyone dumb themselves down to some arbitrary level. How will the true geniuses ever shine if we require everyone to be of the same brightness?

      And no, I don't consider myself to be one of the geniuses who should be excused from the normal policies, I just think that if we allow this kind of thinking to take root, we'll be selling ourselves short (as a company, or country, or species, take your pick) of what we could otherwise achieve.

      Sure, that will make it harder as the number of people increases (as you have a tougher time picking out the true geniuses from the rest), but I do not think we should be using "finding real talent is hard" as an excuse to make "just enforce mediocrity" our policy.

    17. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 1, Informative

      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.

      The frilly article said nothing about not commenting code. It is against silly comments.

      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.

      I don't want to write comment free code, but I also realize that extensive commenting is stupid and counterproductive. I have seen too many instances of code, where nearly every line of code is commented and most of those comments add absolutely nothing of value -- on the contrary, the comments just make the code more difficult to read and add to the burden of maintenance.

      I have also seen too much "if-then-else-switch-for-break-continue" code, where the extensive commenting is a symptom of absolutely awful code. Fix the code and you can at the same time get rid of most of those comments, while still leaving the code more readable than it was before. Generally, if you need more than three levels of indentation, you should really consider for a moment if you could structure the code better. The same thing with ifs, switches and other control structures; if you have a 30 line mess of control structures, you're quite likely doing something wrong and instead of adding to the mess by writing another 30 lines of comments, you should think about ways to make the code simpler (something that might be understandable with a short single comment).

      Some people have a stupid notion that the more comments you write the better, but that is simply wrong. Over-extensive commenting can be almost as bad as not commenting at all, because it bloats the code base (more to maintain, since comments must be maintained as well!), makes the code less readable and because it drowns out the really important comments. The important things to comment are functions (especially if you want to generate API doc from the code), loops that aren't obvious (commenting invariants if often a good way to do this), and constraints and gotchas (ie. if there's some API/platform/algorithm imposed limitation or requirement, don't expect the people reading the code to know about it, but tell exactly where the limitation or requirement comes from and what it is!). When you're using some commonly used algorithm, it's also good to mention it, since it really helps "getting into" the code, if you know what to expect.

    18. Re:One person's myth is another person's fact. by Draek · · Score: 1

      If you can tell the two apart with 100% accuracy, then you can skip writing comments.

      Unfortunately, I've never met a developer that could.

      I can. To my own standards.

      The thing that everybody always misses, is that the difference between a "good" and a "bad" comment is entirely subjective. Sure, most people would agree that a "returns X" comment for a get_x() method is useless, and most would say that your average Perl one-liner must always be accompained by a suitable comment, but its in that nebulous middle ground where opinions are split, depending on the programmer, his team, their respective abilities and experience, the time-frames involved and myriad other factors.

      So most people try to guesstimate conservatively, and comment more than they feel they should. But even then, it only takes one unusual programmer or a stupid manager with the idea that "everything should be commented" no matter how trivial, and we get yet another "proof" of the average programmer's supposed arrogance and disdain for commenting their code.

      --
      No problem is insoluble in all conceivable circumstances.
    19. 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.

    20. Re:One person's myth is another person's fact. by DrLang21 · · Score: 1

      I think that a myth of software development is that every line of code should always be simple and easy to understand.

      No one here is saying that. They're just saying that you should comment it, so that if it is complex, the next guy can figure out what you did without spending days thinking about it.

      --
      I see the glass as full with a FoS of 2.
    21. 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

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

    23. 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.
    24. Re:One person's myth is another person's fact. by michaelmalak · · Score: 1
      "The price of maintaining comment-free code is well known."

      Well, of course, if you take an industry average -- because you have the following:

      • Inexperienced programmers thrown into an old and unexciting "maintenance" project (often H1B's who have no choice but to stay on the job). To understand someone else's code requires years of experience in that genre of language (if not that particular language itself) to understand the common idioms and patterns to reverse engineer. The maintainer needs to be able to say, "oh, yes, that is what they're doing." Like Scotty did with the Mac.
      • Illiterately named symbols. Let me explain what I mean by "illiteracy". I mean the inability to think and to communicate. Any well-thought out comment could instead be put into a variable name with a little thought. As an example, one of the worst offenders is "type". A variable called "DisplayType" is meaningless and communicates no information. "GraphicsAdapter" is much more descriptive, and more OO.
      • Exacerbating the above is code that was written in the era before auto-complete and by those who couldn't type. Those people tended to create variable names that were too short, often just acronyms and abberviations.

      I use comments only in the following situations:

      • A one-line hyperlink for an entire module or source code file that links to the algorithm or approach I am implementing.
      • Documenting how I am working around a compiler or API bug.
      • Documenting how I am working around a bad database schema (this can lead to all sorts of kluge code).
      • Adding a TODO or noting temporary code.
      • If it's code not written by me, documenting shortcomings and limitations of it.
      • Mark off sub-sections of code, especially in super-long procedures. (In the interest of preserving code locality, I do not break up super-long procedures unless the sub-procedures are actually called from somewhere else.)
      • In the spirit of Knuth's literate programming, I will often do ASCII art to create UML diagrams -- always for state machines, and sometimes even for class diagrams when they are deep. Obviously, my execution is different than Knuth's -- no special tools are needed to extract the documentation -- just an ASCII editor, and that is the beauty. Not only do I know the diagrams accompany the code, I know the recipient will both know they exist and be able to read them without additional tools.
    25. Re:One person's myth is another person's fact. by mandelbr0t · · Score: 1

      It's clear you will play the bureaucrat, requiring all red tape to be completed in triplicate before one may use the stapler. You will never pay me because I will never work for you. If you're going to manage people, you have to understand how they work, and even if you think you do, even if you were once in that position, it's obvious you either forgot or learned in a different era.

      Beautifully worded rebuttal to this cynical greybeard. I'm surprised his post didn't end with "Get off my lawn". I don't want his reference, or to work for him. I don't need to get paid to find code to write, and it's infinitely more enjoyable than the business ideology of how software development is supposed to work. Software engineering is a new discipline, and there's still a lot of arguments from both sides to be considered. OP is assuming as fact many things that are still being examined.

      Lest people think I'm am simply trolling, I'm not saying that software engineering has no purpose, and that it's always wrong to use those methodologies. But a corporate intranet application is not software for the Space Shuttle.

      --
      "Please describe the scientific nature of the 'whammy'" - Agent Scully
    26. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      Comments, like most writings should be directed to the intended readers. Having said that, I find the most useful tool for efficient software maintenance is just using good names and naming conventions . I hate to belabor the obvious but people communicate with words and using appropriate words is essential for accurate communications.

      Anyway this topic has been covered to death. The best summary IMHO is found in Steve McConnell's "Code Complete". McConnell to his credit and unlike most posters here tries to support his recommendations with the results of the few experiments that have been done.

      Coding is easy, understanding is hard.

    27. Re:One person's myth is another person's fact. by JWSmythe · · Score: 1

          Sometimes the "#hack to be fixed later" are very useful if you are consistent, and go back and fix them before handing it off. I'll put those in, knowing I'll fix it before it's done. I've been known to put "#HERE", at the end of the day, just to remind myself the next morning where I had stopped at.

      --
      Serious? Seriousness is well above my pay grade.
    28. Re:One person's myth is another person's fact. by WaywardGeek · · Score: 1

      Very nice first post! I was thinking of writing much the same thing. Comments help teams of people work together. Poor team players either don't comment, or let them get out of date. Stupid large companies require useless comments with lots of parsable syntax, like AUTHOR, and DATE on every function. For teams, the middle ground is the best - comment each .c file's purpose at the top, have at least a short phrase for each function, and keep functions small with meaninful names. Use meaninful names for variables.

      Some programmers are too amazing to ever work well with other programmers. I consider myself one of the best I know, but I'll mention the best I've ever met. Ken McElvain, founder of Synplicity, is a Mozart with code. The first day I went to work for him, there were 350K lines of code, 100% written by Ken. I opened a key algorithm file, which was 2000-ish lines. It was 1 freaking function! I tried to understand what was what, but most variabe names were 1 letter, and the rest were 2. There were no comments. I got a bit freaked out, so I grep-ed the entire code base for a comment. There was one: "This is a hack." To this date, I do not believe any other coder ever figured out how that particular function with that comment works.

      Watching Ken code was amazing. He had two large screens full of icons, each programmed to do a different function, like "release code to build servers." His programming speed was limited by his typing, and he was very fast. Thus the 1 and two letter variable names. He always wrote code from the top of the file to the end, and then hit the "compile and run, optimized" button. He's the only programmer I ever met that by default compiles new code in release mode. Typically, he'd write synthesis algorithms he'd invented over night, and it usually turned out to be the best ever seen. He didn't even bother to read all the papers on how others do it. It was just amazing to watch.

      However, it got ugly when he'd hand his code to another programmer (like me) to take over. I suspect most programmers early on at Synplicity spent most of their time fixing bugs they'd introduced because they didn't understand the full extent of what the original code was suppose to do. To get to 2X the producivity of just Ken, I think we had to have a team of around 20 very good programmers.

      --
      Celebrate failure, and then learn from it - Nolan Bushnell
    29. Re:One person's myth is another person's fact. by nwf · · Score: 1

      Yes, this is the main reason I end up placing comments in the code (not around a function body, which I only do when I want JavaDoc for something not entirely obvious.)

      Code that interacts with other code can make things complicated, so adding a comment stating why things were done in one place in order to support something else are helpful. Commenting complex code is handy, too. However, most code just isn't complex if written well, but there are cases where it needs to be complicated. (Implementing non-obvious mathematical formulas, for example.)

      OK, I lied, another case is to document lock ordering for concurrent code. I typically comment the prerequisites for calling a function, e.g. "queue must be locked before calling." Keeps me from having to remember my clever assumptions. Oh, and documenting internal file / network structures is a good idea.

      --
      I don't know, but it works for me.
    30. Re:One person's myth is another person's fact. by zill · · Score: 1

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

      That really depends on the language and the machine architecture. Since the compiler has a better grasp of both, it's better to let it make the decision for you.

      Plus it invites this type of dangerous thinking: "If left shift is multiplication by 2, then right shift must be division by 2!"

    31. 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
    32. Re:One person's myth is another person's fact. by owlstead · · Score: 1

      In Eclipse (an IDE, mostly used for Java) you can create comments that automatically generate "Tasks". These tasks are then displayed in the "Task View", for instance when a comment contains TODO: or DEBUG: or NOTE: or WARNING: which are the tasks that I have defined. In release code, there should be no TODO: or DEBUG: comments left of course. You can also easily look those up in a normal text editor.

      So before releasing it is very easy to take a quick look at the task view to see if you've got any loose ends. The hacks are of course tagged with a "WARNING: ugly code, should use an unmodifiable HashMap instead of two arrays" or something similar.

    33. Re:One person's myth is another person's fact. by markov_chain · · Score: 1

      I really hope you don't write code comments like you write slashdot comments ;) You lost me after 3 paragraphs...

      --
      Tsunami -- You can't bring a good wave down!
    34. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 1, Informative

      Let the compiler do its job. It can optimize better than you can and your code will be more readable.

    35. Re:One person's myth is another person's fact. by Lord+Kano · · Score: 1

      The more code you write, the more important it is to comment for your own use. Have you ever come across some code that you wrote 3-5 years earlier and said "Why did I do that like that when doing it like this would be so much more efficient/better?" I have. Have you ever started to rewrite your code with the thought that you can do it so much better now? I have. Have you ever spend three hours rewriting your code only to figure out that there was a reason why you did it the other way in the first place? I have. That's why I comment my code. Not necessarily for the guy who has to maintain it next, I do it for me.

      LK

      --
      "Hi. This is my friend, Jack Shit, and you don't know him." - Lord Kano
    36. 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
    37. Re:One person's myth is another person's fact. by Lennie · · Score: 1

      I use geany with PHP and VC-plugin for git. Works very well as well.

      (dutch is not my first language)

      --
      New things are always on the horizon
    38. 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
    39. Re:One person's myth is another person's fact. by Brian+Gordon · · Score: 1

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

    40. Re:One person's myth is another person's fact. by Lennie · · Score: 1

      I have a feeling he creates lots of classes, probably so many classes you can't even see the forest anymore.

      Please, keep it simple.

      --
      New things are always on the horizon
    41. 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.

    42. Re:One person's myth is another person's fact. by xtrafe · · Score: 1

      Proven? Where? Even if it were true that commenting is useful in some situations, are you certain it universally increases productivity? Given your degree of certainty, why did you omit the study that supports your point?

      It is my experience that code commenting encourages people to not read code. Commenting an API is a great thing, since it aids encapsulation. Commenting class-internal methods might be a bad thing, since someone who is trying to understand how a class works really ought to be reading and understanding all of the code. Also, lets not forget that code is a _human_ language; the code itself says what it is doing. Finally, programming has changed a lot over the 'decades' you speak of. Are you sure that the habits that were formed when people were programming pascal in a waterfall development process are equally applicable to C# in an Agile environment with an IDE that can instantly jump to any method declaration?

      I'd humbly like to encourage you to be a little more analytical an open minded about your coding practice beliefs. It's also my experience that there typically is an inverse relationship between how good a programmer one believes oneself to be, and how good of a programmer one actually is.

    43. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      Comments in code only serve the purpose of ensuring that someone can reuse your code. Code reuse is such the trend, the whole world wants to copy and paste everyone else's stuff so much so that people dont even bother learning how the code itself works, just what it does. If you know how the code works, you dont even need comments, which never stay up to date anyway, unless your a govt monkey or working for a big company where they pay you to write one line of code a week. I say, learn how to program and you dont need comments, you can actually just read the code.

    44. Re:One person's myth is another person's fact. by gadzook33 · · Score: 1

      Aren't you just on the other extreme here? It sounds like TFA is almost completely against comments, and you're saying that we should comment as though we're always writing the weapons control system for an F-22. Isn't the real answer almost always somewhere in the middle?

    45. Re:One person's myth is another person's fact. by DLG · · Score: 1

      Thank you for writing almost exactly what I wanted to say. I went through a weird emotional response. I almost want to call the writer a young whippersnapper...

      It is pretty funny to say you aren't going to buy into dogma when nothing you are talking about is dogma. Even best practices are often stated in contexts. I won't reiterate the excellent rebuttals to the blog both on the blog and here.

      ---------------------

      The more brilliant and exciting the code you write the more likely it is not a trivial and obvious solution. If all you do is code obvious solutions to common problems in standard idioms then you may be able to argue that your comments do not matter.

      If you are writing something that was difficult for you to write (and the best programmers are lazy enough to try to avoid always rewriting trivial solutions) then you also are writing something that is difficult for not only other coders, but for YOU. That is to say that solving a complex problem in an ingenious and elegant way does not automatically mean that you will understand it later. Even a few months later you are going to wish you had explained some of the why and some of the what.

      In the end most programmers comment only when they feel it is necessary. It isn't really enjoyable, it does take effort. Mostly we do it because we must. Depending on the language and context, you may be writing very formal documentation as part of your project, and some of that may be in the code itself. Other times, you write code that you think is a one off, and then somehow it ends up being a large project and suddenly you need to go back and comment to make it possible to hand it off.

      I do feel as if the fellow who wrote this blog was not an experienced coder, and had never worked with other programmers...

    46. Re:One person's myth is another person's fact. by zill · · Score: 1

      Again, it's language and architecture dependent, but in my case (C99 on x64) the following code produces the wrong result:
      printf("%i",-1>>1);

      In fact, right shift is not equivalent to division by 2 on all machines that use two's complement for binary numbers. So we're talking about at least 99% of all computers out there.

      Of course your language/compiler/architecture of choice may not have this problem, but at least right shift is not universally equivalent to division by 2.

    47. Re:One person's myth is another person's fact. by digitig · · Score: 1

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

      It doesn't need to be commented, it needs to be commented well. I've seen far too much code in which the comments simply repeat the blindingly obvious -- heck, I've written it myself when working in environments that have required that everything be commented. But as the RA says, there are times when comments are useful. A couple of examples -- stating at the top of a routine important stuff that can otherwise only be found out by digging deep into the code (is a sort stable? are there restrictions on the values of the parameters?) and stating why something is done a particular way (ok, that's a slight smell, because it should be in the design documentation, and all projects have comprehensive design documentation, right?)

      So writing /* Gets x */ as a comment describing the operation of a function double GetX() is indeed noise, but typical of coders working to satisfy arbitrary code metrics. Writing /* Gets boiler temperature in degrees Celcius, accuracy no better than 0.1 degrees (may be worse depending on sensor hardware. Refer to documentation on the actual connected sensor). Result will be clipped to the range 0.0 through 120.0 */ describing float GetBoilerTemperature() is not noise. Just don't expect to be able to check which you are getting by doing an automated check on comment lines per SLOC. This needs human review.

      --
      Quidnam Latine loqui modo coepi?
    48. 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?
    49. Re:One person's myth is another person's fact. by ShakaUVM · · Score: 1

      >>So instead they say things like: /* yeah, I don't like this either */

      Yeah, we've all seen bad comments like that, but there have been a number of times when comments have been life savers, beyond simply saying what it is a block of code is doing:

      Once, when using a weird language, there was a note to not add any new member variables after a certain one. You could add new member variables above, but the ones below that point had to be fixed in place for the interpreter to function correctly. Without that comment, I'd have spend hours going insane trying to figure out what was crashing my code.

      Similarly notes in code that say something along the lines of, "If you change this, look at module X over there to make sure you don't break it." Even when you use encapsulation and patterns like connectors, sometimes you just get stuck in a situation where two different modules have to know about each other, and the logic interfacing them has to go somewhere.

    50. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      I forget my C standards trivia, but are you saying that C doesn't require sign-extended right shift when operating on a signed operand, or that compilers are broken, or that you need to cast the "-1" constant to a signed type before shifting it?

      If I were writing that kind of code, I would have done "( (int32_t) -1 ) >> 1" or similar according to the local code convention for portability to document the expected operand type and therefore the expected shift mode, without any comment being required.

    51. Re:One person's myth is another person's fact. by Bill+Dog · · Score: 1

      This is error-prone, tho. Comments do help you to not forget your clever assumptions about a function, but what will help you to not forget to always check the code for every function you call, for such comments?

      --
      Attention zealots and haters: 00100 00100
    52. Re:One person's myth is another person's fact. by The+MAZZTer · · Score: 1

      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.

      That just makes it easy for them to fire you and replace you. Badly written code that only YOU have the ability to maintain ensures your job security! ;)

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

    54. Re:One person's myth is another person's fact. by Mr2001 · · Score: 1

      I forget my C standards trivia, but are you saying that C doesn't require sign-extended right shift when operating on a signed operand, or that compilers are broken, or that you need to cast the "-1" constant to a signed type before shifting it?

      The first one. The behavior of the right shift operator is unspecified (implementation defined) when operating on a signed negative value.

      --
      Visual IRC: Fast. Powerful. Free.
    55. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0
      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.

      Or are actually significantly more skilled than you and you simply cannot recognize it.

    56. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 1, Funny

      Holy crap, is there a way to upload this to my kindle so I can read it in its entirety on my next plane flight?

    57. Re:One person's myth is another person's fact. by Surt · · Score: 1

      No, I assure you, that is clearly not the case. I can definitely tell the difference between the people who might be smarter than I am, and those who turned in a crap solution.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    58. Re:One person's myth is another person's fact. by R3d+Jack · · Score: 1

      My opinion is you're a stubborn idiot.

      My opinion is that a person's judgment usually reflects more on themselves than on the person they judge. Back to the original post, it seems a bit silly to me. I've spent countless hours figuring out why some journeyman programmer wrote code they way they did with no benefit from comments. At the same time, I've wanted to remove all the comments from code because they were verbose but contained little real information. Both are equally bad practices; why debate about which is worse, or use one bad practice as a counterpoint support to another bad practice?

      Bottom line is, *I* have found well-written code, with brief but meaningful comments, the easiest to work on. And I don't recall meeting a person who advocates code with no comments who struck me as a solid programmer.

    59. 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.
    60. Re:One person's myth is another person's fact. by Surt · · Score: 1

      To clarify: I can definitely recognize someone significantly more skilled than I am, because even I, at my level of dumbness, know to dumb down my answers further for the audience, so clearly the higher skilled developer does also. Their failure to do so either indicates a deficit in people skills or disdain for the job, and either way, we don't want to hire that person, it's bad for team morale, and we have a large enough product suite that we can't do without the team, no matter how fantastic the rock star godly programmer is.

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

      And if your resume passed my desk, you would not be hired.

      I have to ask.. what in the world is your problem? It sounds like you wish to torch anyone who does not use the exact amount of commenting you do. Engineering is about tradeoffs, and comments are no exception, that is all the piece said.

      It did not even say 'do not comment', just to be aware of the cost/benefit and make a decision based off that.

      If you are encouraging people to take a blind dogmatic approach rather then doing the work to determine what the appropriate amount is, then I question how effectively you can apply it. To be blunt, it makes you sound like another type of hot shot that is an equal bane to the ones you are complaining about.

    62. Re:One person's myth is another person's fact. by kharchenko · · Score: 1

      Christ! You fail to grasp most trivial matter - comments are needed for someone to quickly interpret your code. As the gp said, if you're writing for yourself - do whatever, but nobody else wants to waste time "disassembling" some crap you wrote during a stroke of brilliance at 3am on Saturday after five five vodka-redbulls. What you may consider "unimportant" in some cases actually is confusing, and will benefit from brief comment or two. Given the length of your rant, you obviously don't have a problem typing things up. So I would certainly get on board with that prototypical old guy you're bitching about and tell you to suck it up and do it.

    63. Re:One person's myth is another person's fact. by swillden · · Score: 1

      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.

      Somewhat off-topic, but getters and setters are one of the things I most dislike about current Java programming style. They're made somewhat necessary by the language, and very necessary by the libraries, but that's really unfortunate. Everyone should take a gander at how Python approaches properties and be enlightened.

      For those who aren't familiar with Python (note: I'm not holding Python up as some paragon of language virtue; just pointing out that this is one thing the language gets right), in Python there is no need to write getters and setters.

      Typically, properties start their life represented directly as private data fields. By hiding the data fields and exposing them only through getters and setters, we make it possible to change the representation of the property from a field to something else later, or to attach a little additional behavior. It's fairly rare that the flexibility is ever used, however. Generally, those fields wrapped in getFoo/setFoo methods just stay fields forever, and the getters and setters stay simple forever, meaning that there was no value in hiding the data to begin with. It would have worked just as well to make them public fields.

      In Python, if your property's most convenient and useful representation is a public field, you make it a public field. If at some future point in time that changes, then you can reimplement the property with a getter and a setter, and client code doesn't have to change.

      Thus, you eliminate page after page of useless boilerplate code, without losing flexibility. A future version of Java should allow private fields to be annotated as properties, causing getters and setters to be implicitly generated, and recommended Java style should change to use field-style properties rather than getter/setter-style properties wherever they make sense. Client code should always use the getters/setters. Some code generation tools do this already, but it should be moved into the standard compiler. Or something equivalent should be done. Having pages of getters and setters in our code, even if auto-generated, is just dumb.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    64. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      If you started coding and management hasn't provided a spec, then management are the ones who should be fired.

      If you have a functional spec, it should already tell you everything you need to know about what the code is (supposed to be) doing.

      I'm not saying there is never a need for comments; but documentation belongs in the documentation.

    65. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      f data-hiding is always enforced, there are page after page of code which require absolutely zero comments because they are just get/set methods.

      Gak! If you have pages and pages of get/set methods it sounds to me like whatever you're doing has insufficient metaprogramming.

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

    67. Re:One person's myth is another person's fact. by thermal_7 · · Score: 1

      That's assuming that comments add a significant amount time to a project. Granted, that extraneous comments are not a good thing, however the whole reason it is considered a good idea in the community, is because a comment takes 10 seconds to write for the developer. When you wrote a piece of code you know exactly what it is doing and can comment with very little effort.

      You also need to consider, that it is dangerous not to have standards on when to comment. You may be very good about only commenting when appropriate, but there are many developers who put simply suck. They either write confusing code, or they just don't think too much about comments and add them almost randomly. With strict standards, you get a product that has been commented consistently, even if somewhat extraneously, which is a lot better than a lack of comments.

      As an example, you can comment methods in C# describing the method and the parameters which then show up in intellisense (tooltips). You could only comment methods that are not immediately understandable from the name of the method. But then, you don't know how other people might interpret these names. So you then play it safe and do ones that could be slightly confusing. Then you have 90% of them commented and the other 10% missing, which will likely concern other developers as to why they are missing. So, it is generally not worth the tiny amount of time you save being selective with comments.

      The other aspect is, I think it is excellent practice to write comments before you code. This way, you often find flaws in your logic before you write any code, thus saving time. Once it is all good, then you just fill in the blanks, in which case commenting doesn't add any time at all.

      It's a big assumption to say that all future developers to look at a block of code will understand it, especially when to you as the developer who wrote it it is all obvious.

    68. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      You... you refuse to hire people because they won't dumb down their answers? Are you serious? Maybe you're just insane. What company do you work for, I'll make a point of avoiding their stuff.

      Seriously, you honestly expect people you're interviewing to NOT be at their best? I'm sorry, I don't mean for this to come off as a personal attack by any means, I'm just completely baffled. My mind has received SIGSEGV.

    69. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      I agree with most of what you said. When you're doing professional code on a very tight deadline you may not always have time to come up with some amazingly clever magical self-documenting but still lightning fast implementation of an algorithm -- a comment is just the best time and money will allow you.

      I've also inherited TONS of code from programmers with the 'self-documenting' code mindset. Self-documenting to you is not always self-documenting to me -- especially since at the time you probably had a much firmer grasp on the system as a whole (which of course, is not documented either).

      I disagree with the 'hack' comments though, sometimes comments are a 'note to self' from the original programmer, and that's not incredibly abhorrent. Like I said above, in a professional environment on a tight deadline it may be more important to get something quick and dirty up and running so others can begin using the interface *before* you tidy up the internals. Unfortunately, the time often never comes up to do that, and the hack is left in place for years. Anyhow, my counter-argument is that these comments have nothing to do with embarrassment or insecurity, but were just (intended to be) temporary comments by and for one person.

    70. Re:One person's myth is another person's fact. by Brian+Gordon · · Score: 1

      No that's a rotate, not a simple shift. Or do you mean shifts into the carry flag?

    71. 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
    72. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      pretty clear that you enjoy typing verbose comments...just add a /* at the beginning and */ at the end and you're done!

    73. Re:One person's myth is another person's fact. by donscarletti · · Score: 1

      A left rotate will write the MSB into the LSB, which is never the sign bit. Anyway, the grandparent is far more wrong than you are, since the MSB _IS_ the sign bit (not that you should be doing bitwise operations on a signed value anyway).

      --
      When Argumentum ad Hominem falls short, try Argumentum ad Matrem
    74. Re:One person's myth is another person's fact. by grimw · · Score: 1

      I have, and then, after getting more experience, I've decided it's best not to fix code that's not broken (i.e. is not optimal or does not have any major anti-pattern in it). Besides, as you gain more experience, you will be able just to read your own code and figure out why you did something a particular way. If you really did have an obscure reason for why something was done a particular way, put a very brief comment, but don't make a drawn-out explanation that is boring and difficult to maintain as the code is updated, because a comment is worse than no comment if it's an incorrect comment.

    75. Re:One person's myth is another person's fact. by emmons · · Score: 1

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

      You may benefit by taking a look at Joel Spolsky's opinion of that particular hammer.

      --
      Do you even know anything about perl? -- AC Replying to Tom Christiansen post.
    76. Re:One person's myth is another person's fact. by dave87656 · · Score: 1

      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.

      The issue is not whether you should comment your code or not, it's what you should comment. It's finding the right balance which makes your code maintainable. I've seen code with very little comments which was very understandable and code with alot of comments which was virtually impossible to follow.

      I knew one programmer who commented every line, no matter how obvious. But his code was still not maintainable. For example:

      No comment, but readable: "balance += deposit; "

            versus

      Comment but useless: b += d; // add d to b

    77. Re:One person's myth is another person's fact. by emmons · · Score: 1

      JonKatz.. oh those were the days!

      But I agree, sections like that would be quite useful.

      --
      Do you even know anything about perl? -- AC Replying to Tom Christiansen post.
    78. 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.

    79. 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?
    80. Re:One person's myth is another person's fact. by Wildclaw · · Score: 1

      for applicants to my company

      This is a selection problem. Applicants to your company are not a randomly selected sample. Those who are applying to your company are mostly those who hasn't managed to get employed by someone else. And such a sample therefore says little about the programmer population as a whole.

    81. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      Ugh. At some point we seemed to have lost our bearings on what coding is. Coding is not writing code and comments (otherwise they'd call it "coding and commenting"). It's writing code. It is precisely the effort to make your code self-documenting that helps your thinking and understanding of the code and in developing without bugs. No need to introduce a secondary mechanism to do this, adding unnecessary artifacts to the code.

      Dang, I can't believe I have to tell Steve Wozniak this.

    82. Re:One person's myth is another person's fact. by ArundelCastle · · Score: 1

          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 don't wish to be abrasive, but you're basically saying because it's beyond your grasp, it's a lost cause? What if another programmer comes and rewrites the code in a "better" language for the task?

      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.

      You've just contradicted yourself. It's overcommented in case someone, like a web developer switching from IIS to Apache, needs to reference it. What you've been known to do is something that I've known almost every coder to do. Strip comments from production code, and leave them in the debug.
      Apache isn't providing bloated files, they're saving thousands of people from forgetting to make their own .orig copy, and having to spend more than 4 seconds to restore a working version if it breaks the server.

    83. Re:One person's myth is another person's fact. by Bill+Dog · · Score: 1

      I'll put my name in as a "comment" and what I need to do next, like:

      BILL: STILL HAVE FUNCTION FOO TO FINISH UP BEFORE BAR

      But not actually as a language comment, so that I'll get a compile error in case I forget that I left myself a reminder. I've found that my biggest source of bugs is being switched off to something else and returning back to a task and not only forgetting where I left off by file and line number but also in my train of thought.

      --
      Attention zealots and haters: 00100 00100
    84. 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.
    85. Re:One person's myth is another person's fact. by Tony-A · · Score: 1

      Yes it is error-prone.
      However not having ANYTHING commented is much more error-prone.
      You are not going to write anything non-trivial that does not have error.
      Your only choices are which errors and how many and some of what the (unforeseen) consequences are.

      Maybe the best comments are those written with the attitude of "What would I need to know if I weren't the one who wrote this stuff?"

    86. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      (A different AC here)

      If you really suspect that you're going to have mostly dummies working there over the years, such that the bar needs to be kept pretty low in the code, maybe you shouldn't be considering any geniuses then and save both yourself and them the time.

    87. Re:One person's myth is another person's fact. by Tony-A · · Score: 1

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

      Horse-hockey.
      If he had time and ability to document exactly what was wrong with it, then he would have fixed the mess instead of commenting on it.
      Any existing code is the result of some kind of trade-offs between what is needed, when it is needed, and the resources available.
      On the information highway, it has to be useful to distinguish between expressways and goat-trails.

      When code need to be revised, your own or somebody else's, the first thing I would want to distinguish is whether is is better to modify the existing or to do a complete redesign. You somehow seem to believe that the original writer has better foresight of my current context than I can have.

      Now quick, what is it about Windows 7 that makes it fragile?

    88. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      My opinion is you're a stubborn idiot.

      I stopped reading there. Troll somewhere else.

    89. Re:One person's myth is another person's fact. by Tony-A · · Score: 1

      > That's assuming that comments add a significant amount time to a project. Granted, that extraneous comments are not a good thing, however the whole reason it is considered a good idea in the community, is because a comment takes 10 seconds to write for the developer. When you wrote a piece of code you know exactly what it is doing and can comment with very little effort.
      Dunno about you, but for me, knowing exactly what the code is doing is barely possible in extremely well designed Assembler code and far from feasible in anything "higher-level".

      > That's assuming that comments add a significant amount time to a project. Granted, that extraneous comments are not a good thing, however the whole reason it is considered a good idea in the community, is because a comment takes 10 seconds to write for the developer. When you wrote a piece of code you know exactly what it is doing and can comment with very little effort.
      Very correct. The absence of a comment must be indicative about the state of the code quality.

      > The other aspect is, I think it is excellent practice to write comments before you code.
      I've never seen it done, but that would be very workable and productive.

      > It's a big assumption to say that all future developers to look at a block of code will understand it, especially when to you as the developer who wrote it it is all obvious.
      I have found that it is almost never obvious to me, after as little as 6 days, let alonw somebody else after 6 years. It is easy to write something and convince yourself that it makes sense, without it ever having made sense. This is significantly easier to do with "meaningful" names and "high level" languages. The problem is that what works and what does not work depend on the location of the edges and corners and where they impact the environment as things twist and turn.

    90. Re:One person's myth is another person's fact. by Bill+Dog · · Score: 1

      The other aspect is, I think it is excellent practice to write comments before you code. This way, you often find flaws in your logic before you write any code, thus saving time.

      Or you could just declare your classes and stub out your functions before you code. Then the names of those classes and functions become the comments, and you can find flaws in your logic from those. And it's stuff that you're going to have to write anyways, saving time (over writing it in a different way first, such as in the form of comments).

      For example, if you're planning to write a function that does three things, containing three non-trivial blocks of code for doing them, don't write the function signature and then place three comments in the body, to help you go over your plan. Instead place three function calls in the body, with names that convey what you would have commented about.

      --
      Attention zealots and haters: 00100 00100
    91. Re:One person's myth is another person's fact. by lena_10326 · · Score: 1

      You have a low user id, and your journal consists of complaining about slashdot moderation. I'm guessing you're old, having moved from coding long ago to managing a team, and

      Having a low or high user id is meaningless when it comes to indicating age or experience. One could have joined in 1998 at age 15 and now they are 27. One could have been a reader for ages and signed up late.

      --
      Camping on quad since 1996.
    92. Re:One person's myth is another person's fact. by keean · · Score: 1

      On the systems I have coded for right shift in C has always been a logical shift, not an arithmetic shift. There is no way to do an arithmetic shift from C, so you have to use inline assembler.

    93. Re:One person's myth is another person's fact. by jrbrtsn · · Score: 1

      Run the source file through the GNU 'indent' program, and the indenting will be perfect. Use a better text editor. Vim understands the difference between a commented brace and an uncommented brace. Vim even understands '#if 0 ... #endif', which is a common way to comment out large blocks of code.

    94. Re:One person's myth is another person's fact. by mattpalmer1086 · · Score: 1

      Absolutely! In my previous job (many years ago), I insisted that developers mark areas of dodgy code with a few standardised comments, like: //KLUDGE: reason for kludge

      The rationale was that we often had to kludge things up to hit silly deadlines, but at least we knew where these dodgy bits of code were so we could clean them up later, and to look at them in particular when we hit wierd bugs. The other side of marking the code like this was I published monthly metrics to the team and to senior management - the "Kludgeometer", broken down by different areas of the code. Once that number started getting high in a given area, it got a whole lot easier to win support to clean the code up - and they eventually agreed to keep the number within reasonable tolerances across the entire codebase.

    95. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      No it can't because usually it doesn't have enough information.
      i / 2 is not the same as i >> 1 unless you know that i is >= 0 always.
      Which _you_ might know in many cases, but the compiler might not.
      So it comes down to which is worse:
      writing
      (unsigned)i / 2
      or
      i >> 1
      with the former still giving the compiler a lot to mess up and probably resulting in different code when compiling without optimization and thus possibly making debugging harder?
      And I seriously wonder if those people saying "the compiler can optimize better" have actually looked at compiler-generated code. While there's no way I would want to write everything in assembler and most of the time it just doesn't matter, it shouldn't take you more than a month to see the compiler doing something _incredibly_ stupid (like actually generating an instruction for a integer multiplication by 0) when seriously working on any kind of code.

    96. Re:One person's myth is another person's fact. by pydev · · Score: 1

      The price of maintaining comment-free code is well known.

      No, it isn't known at all, since there are no sound studies on the subject. You're simply jumping to conclusions.

      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.

      Based on what you have written, I don't think you're a good programmer either.

    97. Re:One person's myth is another person's fact. by pydev · · Score: 1

      The standard comment is:

      # FIXME

      and it is enormously useful. It is so useful that many IDEs actually automatically extract and list such comments.

    98. Re:One person's myth is another person's fact. by awol · · Score: 1

      I find the most important comments are those that tell you WHY something was done the way it was.

      More than most important it is the only reason to comment. HOW comments can only ever be wrong. The code is right (well at least it is what it is) telling how the code does what it does can only be informative by being wrong since even if it is right it is only right insofar as it reflects what the actual code does.

      For this reason, I am not a big fan of comments other than self documenting API regimes since they can be used to adress precisely this point.

      On the other hand I am a fan of literate programming but then that's a whole different story.

      --
      "The first thing to do when you find yourself in a hole is stop digging."
    99. Re:One person's myth is another person's fact. by Carewolf · · Score: 1

      On all machines I've coded for the right-shift on signed numbers have always been arithmetic. While not being a standard it is recommended C, and applies to atleast x86 and PowerPC

    100. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      signed b;
      b/=2; /* Wow, that was hard! */

    101. 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."
    102. Re:One person's myth is another person's fact. by Rockoon · · Score: 1

      What are you talking about? There are PLENTY of reasons to do bitwise operations on signed values.

      In fact some very strong bitwise techniques *require* twos-complement treatment, and Donald Knuth has a new book out for people like you who are still ignorant of the outstanding things thats two-complement can do for you. The Art of Computer Programming, Volume 4.

      --
      "His name was James Damore."
    103. Re:One person's myth is another person's fact. by Rockoon · · Score: 1

      Compilers are good at the tedium of large-scale optimizations such as constant propagation, but are still not up to snuff when it comes to producing tight loops (the place where it usually matters most.) This is why the fastest workhorse libraries are written in assembler (such as encryption, compression, and so forth)

      --
      "His name was James Damore."
    104. Re:One person's myth is another person's fact. by Rockoon · · Score: 1

      Unless you use a really crappy compiler, the compiler will turn a multiplication into a bit-shift for you.

      Only crappy compilers still turn multiplications into bit-shifts, because its simply not superior to multiplication on AMD64/Core2.

      You are living in the past, and so are most compilers.

      --
      "His name was James Damore."
    105. Re:One person's myth is another person's fact. by MikeDX · · Score: 1

      I've had trouble in the past with VIM regarding commented braces as part of the code structure in php files, making the % function fail. Is there a setting for this? Maybe it is just the php syntax highlighter that is broken, and the C/C++ and others work fine.

      Or maybe it's just an old VIM I'm using...

    106. Re:One person's myth is another person's fact. by Tanuki64 · · Score: 1

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

      I don't need to see the code. Loops so big and nested that you need to mark the end of each loop to see, which end of a loop belongs to which loop header. Several developers working on one function. Pasting in a huge number of lines, which in most cases would be too many even for a stand-alone function. A function with 1000 lines always smells. Pasting it in another function spells design disaster almost for sure. So yes, I don't know the code, and I don't know what type of program you were working on. And yes, cases in which a better design is not possible exist, but are extremely rare. So rare infact that unless I am convinced otherwise, I just assume it is the usual example of crap code found in the majority of software projects. And I have never seen a code, which could not benefit from a refactoring. I said on purpose code not project. In a project is due to time constraints a refactoring not always possible.

    107. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      There are other architectures, you know? People worrying about that kind of stuff often write embedded code.

    108. Re:One person's myth is another person's fact. by Rockoon · · Score: 1

      ...or are worried that their crappy compiler is still producing code optimized for architectures a decade or more out of date.

      I would not be surprised if multiplication were no worse than equal to shifts on ARM as well.

      --
      "His name was James Damore."
    109. Re:One person's myth is another person's fact. by belroth · · Score: 1

      Well, you could alwys read TFA and find out what it says, but that's not the /. way.

      --
      I hereby inform you that I have NOT been required to provide any decryption keys.
    110. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      New devices are still produced with 8-bit cores where multiplication is a subroutine. If it's 1ct cheaper, it isn't out of date.

      The point is that writing shifts instead of multiplications is an optimization(-attempt). Whether it fails to improve the result because the compiler would have made the substitution automatically or because there is no performance difference between the two is a moot point.

      Architectures vary and the knowledge about an architecture's peculiarities is best collected in one place, the compiler. I wouldn't be surprised to find that short shifts have a smaller memory footprint, which may lead to shorter jumps and better cache utilization, thus improving the speed even if the single instructions take the same time. The shift might free a functional unit of the CPU for other threads, etc. The programmer should not concern himself with the details. If he does anyway, why is he writing code in a high-level language? The effect of the optimizations is not going to be portable.

    111. Re:One person's myth is another person's fact. by Rockoon · · Score: 1

      The point is that writing shifts instead of multiplications is an optimization(-attempt). Whether it fails to improve the result because the compiler would have made the substitution automatically or because there is no performance difference between the two is a moot point.

      You seem to be missing the point. There are plenty of compilers that still insist on replacing constant multiplications with shifts (you have it backwards!) when it is no longer optimal to do so. It is, in fact, suboptimal to do so.

      The great great whatever grandparent was completely wrong about using shifts instead of multiplication, AND THATS THE POINT. HES WRONG, AND MOST COMPILERS ARE ALSO WRONG.

      --
      "His name was James Damore."
    112. Re:One person's myth is another person's fact. by Alpha830RulZ · · Score: 1

      Software engineering is a new discipline

      How new is a discipline which can now claim that at least three biological generations of man have been involved in it? Consider Hoare and Turing, Kernighan and Ritchie, and the current class of students. Heck, there have been three generations involved simply since I first laid hands to keyboard in the 70's.

      As a Greybeard myself, I have repeatedly run into these types of dismissals of the value of my experience and that of my aged peers. These dismissals usually come from the youngest in the room. While it's good to challenge assumptions, it's also good to consider the possibility that you may not have been the first to do so, and that many folks before you may have done so and come to the conclusion that the assumption is still valid. I think it's logically risky to conclude that everyone before you was a freaking idiot, and that you are now the first person to see the light.

      And please, if you work on my team, comment the big pieces of code.

      --
      I was taught to respect my elders. The trouble is, it's getting harder and harder to find some.
    113. Re:One person's myth is another person's fact. by bingoUV · · Score: 1

      You are right. I'd like to add here that for a programmer to write such comments, he must be able think all the possible ways the thing can be done. Often, the only reason WHY a particular way is chosen is : that is the only one that occurs to the programer at the time and it seems good enough. The simplest way does not always occur to people first.

      --
      Bingo Dictionary - Pragmatist, n. A myopic idealist.
    114. Re:One person's myth is another person's fact. by mike.mondy · · Score: 1

      There's always some noise and quite a bit of discussion on this topic for one very simple reason.

      There's more than one way to do commenting well.

      Heck, for a sample size of *one*, I can say that my commenting varies significantly depending on things like language, size of project, and how hard or obscure the problem domain is.

      In the end, commenting has only one goal -- to promote understanding. Usually that means what/how/why the code does what it does.

    115. Re:One person's myth is another person's fact. by mike.mondy · · Score: 1

      Almost all of our opinions about comments end up relating to the understandability.

      For example:

      Comments like "this is ugly" are OK. Such comments often highlight areas that might break as the code around them changes. Also ... let's not begrudge the programmer who felt he or she could have done better but decided that it wasn't justified.

      Small snippets of code are not usually where comments are most needed. If I really need to totally grok what your (or my old) ten line section of code does, I can work through it if necessary. Comments are much more valuable when they promote understanding of larger pieces of code -- entire modules, functions, class methods, entire classes, etc.

      Things get more interesting when you look at an environment of multiple different applications running on multiple servers and interacting. You want to see things like documentation about the expected interfaces and good error/sanity checking and reporting. But that's really a different documentation topic than program comments...

    116. Re:One person's myth is another person's fact. by fuliginous · · Score: 1

      Comments are good if they explain why a piece of none obvious code is there (relates to your need to meet performance). But primarily they are to me a way to highlight choices in the design/implementation of that code. You say "ignored this option because impossible". They are also useful for showing the way for which parts fulfil which requirements (provided you have such other documentation) or as requirements covering a portion of code in the absence of good separate requirements and design.

    117. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      Calm down. If your point is that compilers could be better and that they sometimes deoptimize because they act on wrong information about a particular architecture: Granted. On the other hand, I know for a fact that there are important architectures where a bit-shift is significantly faster and more memory efficient than a multiplication. The actual point however is that you should generally write what you mean, not what you think is fastest. Early optimization is bug-prone and causes headaches in maintenance. Low level optimization should strictly be left to the compiler, even, and this is important, even if the compiler doesn't produce an optimal result.

    118. Re:One person's myth is another person's fact. by bXTr · · Score: 1

      You forgot to say, "Get off my lawn!"

      --
      It's a very dark ride.
    119. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      Corollary: The more diametrically opposed, outlandish, and unsubstantiated a claim, the more people will hop onto it as if it were the gospel. "Look! I am thinking outside the box!"

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

    121. Re:One person's myth is another person's fact. by Rockoon · · Score: 1

      The actual point however is that you should generally write what you mean, not what you think is fastest.

      x *= 2

      vs

      x += x

      vs

      x
      They all mean the same thing.

      --
      "His name was James Damore."
    122. Re:One person's myth is another person's fact. by keean · · Score: 1

      On second thoughts you are right, it is usually an arithmetic shift. It must have been an unsigned divide I have had to code with a logical shift in inline assembler. Really the right thing to do would be to use ASR on a signed number and LSR on an unsigned number.

    123. Re:One person's myth is another person's fact. by Surt · · Score: 1

      We're actually unlikely to have any dummies, just not all geniuses. The bar doesn't need to be kept low, it just can't be so high that only a genius can maintain it. Frankly, my expectation is that no genius is going to apply for the job ... they can make far more money founding their own company.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    124. Re:One person's myth is another person's fact. by Surt · · Score: 1

      You're correct of course, but the problem is that even as a sampling problem, we're sampling a pretty huge subsection of the programming population as a whole. We get a LOT of applicants, and most of them currently DO have jobs, and have long, sane job histories. I've also worked with these types of people at previous employers, and I have to say, I'm glad my current employer has done a good job of keeping them out.

      So yes, while 4 out of 5 of all programmers are not that bad, I'd actually put the number of the overall population that are that bad at over 50%.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    125. Re:One person's myth is another person's fact. by Asgerix · · Score: 1

      You may benefit by taking a look at Joel Spolsky's opinion of that particular hammer.

      That article does not argue against refactoring, it argues against rewriting your code from scratch. In fact, the author mentions refactoring as a good alternative to rewriting the code.

      --
      Life is wet, then you dry.
    126. Re:One person's myth is another person's fact. by Joe+Snipe · · Score: 1

      It's hammers all the way down.

      --
      Sometimes, life itself is sarcasm...
    127. Re:One person's myth is another person's fact. by NoOneInParticular · · Score: 1

      Yes, I agree. However, I usually find that the comments are the unreadable part, while the code can be followed through mostly without problems. If the code is too hard to read, I might try to decompile the comments.

    128. Re:One person's myth is another person's fact. by Surt · · Score: 1

      Indeed, though the premise of the conversation was that I had run into a coder whose genius was such that I was unable to recognize the fact that I didn't understand his code.

      In reality, I believe that I have properly understood every submission of a solution to our hiring problem, and that most of them have been crap.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    129. Re:One person's myth is another person's fact. by rhendershot · · Score: 1

      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.

      If you pulled such a stunt with me I'd meet you in the parking lot. I'd slash your tires and seduce your wife. I'd sell your kids into some underground market. I'd burn your house and smack you so hard your DNA would be bruised.

      Ok, hyperbole aside, I do want to point out that there are code that do not require any comments. Surely you can think of an example. And there are code that is clear, but still deserves some explanation of intent due to the clarity of the code but the abstractions between it and its supplier or consumer. I'm sure you can think of an example. And there is the case where the existing implementation is replaced entirely with some facility that was not previously available or maybe simply done better. I'm sure...

      In each case the documentation need is quite different.

      My general rule is the longer I spent thinking about it, the more I should probably say about it. That's not one-to-one with code comments though. I might reasonably add explanation to the design and implementation docs if that's the environment I'm in. My general assumption is that I *cannot* explain the code better than the code explains itself. I should *not* mislead the next programmer into a false sense of security or understanding. If s/he is unable to understand the code as written then there's a management issue to resolve regarding skills resourcing, but I *must* not presume I know that person to-be.

      As a pragmatic measure I tend to comment more than I feel is necessary for myself. That's due to an experiential regression issue with my later understanding of what I did earlier ;) That includes TODO or HACK comments for which I can grep; I find that *really* useful. I'd at least have put /*ME yeah, I don't like that either*/ where ME are my initials so I can find it later. I'd probably have put a version marker in there too. And I would want to see a comment explanation of any bit of the code that did something in a novel or unusual way. I often include in such a comment the url that helped :)

      But not having comments at all? I prefer that to badly outdated, imprecise and *incorrect* comments. It's hard to quantify but, when faced with the latter, I find I waste many many more hours finding the original req, asking around, finding the original programmer, etc. than if there were just nothing at all. The code I can believe. When someone contradicts the code there is a bug. I *do* enter bugs on code review of such mis-matches.

      My guess is that in the same day you'd be too busy talking to management. brava.

    130. Re:One person's myth is another person's fact. by mad.frog · · Score: 1

      You seem to have confused "fact" and "opinion".

      Everyone is entitled to their own opinion, but they are not entitled to their own facts.

    131. Re:One person's myth is another person's fact. by v1 · · Score: 1

      he must be able think all the possible ways the thing can be done.

      So, quoting a certain clever someone, "you've just go to think fourth-dimensionally"

      --
      I work for the Department of Redundancy Department.
    132. Re:One person's myth is another person's fact. by v1 · · Score: 1

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

      Well-said. I will have to remember that. I'll rephrase it a bit, "the code only tells you the how, the comments tell you the what and more importantly, the why."

      --
      I work for the Department of Redundancy Department.
    133. Re:One person's myth is another person's fact. by HungryHobo · · Score: 1

      So you've never written a /* yeah, I don't like this either */ comment?
      We've all done it now and then.

      When your neat and tidy chunk of code just won't work and even after an hour of going over it trying to work out what the hell is wrong and eventually you just give up and drop in a messy horrible little snippet of code that you don't even like writing but which works.

    134. Re:One person's myth is another person's fact. by plover · · Score: 1

      I have also seen too much "if-then-else-switch-for-break-continue" code, where the extensive commenting is a symptom of absolutely awful code. Fix the code and you can at the same time get rid of most of those comments, while still leaving the code more readable than it was before. Generally, if you need more than three levels of indentation, you should really consider for a moment if you could structure the code better. The same thing with ifs, switches and other control structures; if you have a 30 line mess of control structures, you're quite likely doing something wrong and instead of adding to the mess by writing another 30 lines of comments, you should think about ways to make the code simpler (something that might be understandable with a short single comment).

      This is the answer I most agree with. Muddy code is not made clearer by comments. Muddy code is made better by refactoring to clearer code.

      I may start out by writing a 100 line method to do all the steps required, but I won't leave it like that. I'll chop it up into small bits, each with a clear name as to its intent. Switch cases can get turned into state patterns (as can if statements, when needed.) Pull those "four-line-if-clauses" apart into four methods that name the intent of the tests they perform. And do you really need to iterate in the same method in which you're organizing the rest of the setup and teardown stuff?

      Finally, ask yourself if you really need to write comments if you provide unit tests that clearly demonstrate how the code is to be used?

      Good method names make it easier for maintainers. Small chunks of functionality make it easier for maintainers. Dependency injection makes it easier for unit testers.

      Most comments are a violation of the Don't Repeat Yourself principle. "How" your code works is expressed in the code. "What it does" should be clearly stated by the method name. "Why" you call it should be visible in the unit tests. Your code is already stating what it's doing to the compilers. If your code is not expressing itself well enough to the humans, refactor it until it does.

      --
      John
    135. Re:One person's myth is another person's fact. by JWSmythe · · Score: 1

        There wouldn't be much of a reasons to change language to change to 30 line function into a 1 line function. Now, if it were throughout the whole code, that would be another matter.

          For the Apache example, theirs is a good reason that it's overcommented, just as you said. For someone like me, it's too much, but I still keep the orig file around for a guide if necessary. Just because I know it inside and out doesn't mean I won't have a moment where I want to see what they said about a particular directive.

      --
      Serious? Seriousness is well above my pay grade.
    136. Re:One person's myth is another person's fact. by JWSmythe · · Score: 1

          I didn't mention it, but I sign and date a lot of my comments, especially when I'm helping someone else. That way, when they go in later to see what I changed.

          # -jws 01/02/2009 - changes to trace xyz bug.
          [code]
          # -jws 01/02/2009 - end changes

      --
      Serious? Seriousness is well above my pay grade.
    137. Re:One person's myth is another person's fact. by JWSmythe · · Score: 1

          Actually, that was an error on my part. In real life I wouldn't have piped the mv, it would have been &&. :)

          And, there's always more than one way to skin a cat. :)

      --
      Serious? Seriousness is well above my pay grade.
    138. Re:One person's myth is another person's fact. by cloudmaster · · Score: 1

      isn't that why we like Unix? :)

    139. Re:One person's myth is another person's fact. by JWSmythe · · Score: 1

          Exactly. :) We don't have to agree on the method, or even the OS, and we can still agree. :)

      --
      Serious? Seriousness is well above my pay grade.
    140. Re:One person's myth is another person's fact. by honkycat · · Score: 1

      Do you honestly believe what you wrote? That documenting why you think your code is a hack, or needs to be replaced, or whatever is actually as difficult as fixing it? Sorry, that's absurd. The programmer obviously has some reason for being unhappy with the code. FFS I'm just asking to write that down---not sure where you got the idea that this means documenting "exactly what's wrong with it." If that's too hard for you, get a new job because that's part of programming. Or do you just write some code that doesn't "feel" right and decide you should optimize it later?

      When code need to be revised, your own or somebody else's, the first thing I would want to distinguish is whether is is better to modify the existing or to do a complete redesign. You somehow seem to believe that the original writer has better foresight of my current context than I can have.

      What are you talking about?

      Now quick, what is it about Windows 7 that makes it fragile?

      Uhhh, what?

    141. Re:One person's myth is another person's fact. by Dzonatas · · Score: 0

      Everybody that speaks a foreign language, do you make them comment what they just said in your language?

    142. Re:One person's myth is another person's fact. by The+End+Of+Days · · Score: 1

      Like all rules, it needs to be expressed as a one-liner. I propose:

      If you feel like you should pat yourself on the back, slap yourself in the face instead.

    143. Re:One person's myth is another person's fact. by petermgreen · · Score: 1

      Well it is.
      Sort of, there are two types of right shift, "logical shift right" and "artithmetic shift right". For division by a power of 2 on an unsigned number you want logical shift while for division by a power of 2 on a signed number you want arithmetic shift.

      For unsigned numbers C does the sane thing but for signed types containing negative values the behaviour is left as implementation defined.

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
    144. Re:One person's myth is another person's fact. by petermgreen · · Score: 1

      You don't actually lose the MSB -- it shifts into the sign bit. But hey, what harm can that do, eh?
      Which is exactly what will happen if you multiply by 2 in an environment that ignores overflows (e.g. most of them)

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
    145. Re:One person's myth is another person's fact. by InterStellaArtois · · Score: 1

      Mindless getters/setters suck. They just result in gobs of code but no useful information. Comments on these would only be written by those with shares in paracetemol brands.

      The canonical example is a message protocol which features gobs of fields, which may or may not be present in a fairly complex hierarchy of message types. The first instinct may be to provide getters/setters at the correct points in the inheritance chain, to ensure messages can only set the fields they ought to. That way the compiler will ensure these class invariants are upheld. But pages and pages of getters/setters are impossible to validate against a spec and just appear to the eye as noise. Then someone comes along and adds a setter because they think its needed and breaks the whole scheme.

      Take instead a single getter/setter which takes fieldname/value, and a bitmap of allowed fields per-message type. Then check invariants each time the single setter is called. Much more declarative and readable to boot.

    146. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      Uhm... it is - if you are dealing with unsigned (or positive) integers.

    147. Re:One person's myth is another person's fact. by aled · · Score: 1

      This is error-prone, tho. Comments do help you to not forget your clever assumptions about a function, but what will help you to not forget to always check the code for every function you call, for such comments?

      Just put a reminder in a comment. Seriously, that would a different problem and the programmers responsibility.

      --

      "I think this line is mostly filler"
    148. Re:One person's myth is another person's fact. by tjwhaynes · · Score: 1

      I didn't mention it, but I sign and date a lot of my comments, especially when I'm helping someone else. That way, when they go in later to see what I changed.

      # -jws 01/02/2009 - changes to trace xyz bug. [code] # -jws 01/02/2009 - end changes

      That looks awfully like something I would expect your version control repository to tell you. For ages we used to labouriously indicate the problem being fixed and included the "blessed" initials of the developer doing the work. Then we got a real VC and this practice stopped. Life got better.

      Cheers,
      Toby Haynes

      --
      Anything I post is strictly my own thoughts and doesn't necessarily have anything to do with the opinions of IBM.
    149. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      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.

      I don't agree with this view when applied to all cases. Unfortunately, the advent of uncompiled code into production environments - such as ASP, PHP, Perl, Javascript, etc - changes this paradigm. Production environments benefit from comment-free code.

      When we pen-test production environments we mark down sites that have commented code, because security by obscurity does provide a time barrier (like a form of weak encryption). This point appears to have been largely accepted by posters here, with many coders preferring to re-write illegible and uncommented code, rather than understand and re-leverage it.

      There are a number of sites online with obscure code, designed to stop users from improving their own experience in order to bolster value in low-cost paid services. Try stripping the time-out code from the RapidShare free-user javascript, for example.

    150. Re:One person's myth is another person's fact. by Nicolay77 · · Score: 1

      I think that you are going to the other extreme, like in a gut response.

      He (the article writer) says: Excessive superfluous comments are bad (point 3).

      You say: No comments are bad.

      Both are right, but no one is answering the other arguments.

      In fact, you both agree about point 2: not all comments make the code more readable, he makes a general statement, you complain about 'hack' comments.

      It seems that it would do you good to read about quantifiers in logic proofs.

      --
      We are Turing O-Machines. The Oracle is out there.
    151. Re:One person's myth is another person's fact. by JWSmythe · · Score: 1

          I'm frequently not blessed with version control. A lot of times it's someone saying "Can you log into my server and fix something I can't figure out?"

          No harm in any version control using the same method I do. :) Mine grew into that. Obviously, it was a good path if others chose it too.

      --
      Serious? Seriousness is well above my pay grade.
    152. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      A constant shift in C is completely equivalent to multiplication and division by powers of two. It is the job of the compiler to translate it to the most optimal instruction.
      However, you would be hard pressed to find an architecture where:
      a>>=b;
      doesn't perform a lot better than:
      a/=pow(2,b);
      In any case, understanding that >>1 == /2 is the job of a C programmer, if you cannot get over it move on to HTML.

    153. Re:One person's myth is another person's fact. by zx75 · · Score: 1

      Yes, I've done that more than a few times myself. Under pressure of a deadline, and the code just needs to work is a situation I have found myself in more times than I would like. But given the nature of my job, it is entirely possible that the code gets done, and then not looked at again for years. Just recently a client came to us for enhancements to a codebase that hadn't been touched in close to 5 years, and there are a few spots that are 'make it work' instead of 'clean and pretty'.

      In this situation I will often flag the section of code with a "TODO" and write a brief explanation regarding how the code SHOULD be structured such as: //TODO: Future Rev. restructure by abstracting common elements from X, Y, and Z and merge object creation into a factory.

      This serves very well as a 'this is a hack' flag to me but also reminds me why it was a hack and what I was thinking on how to improve it.

      --
      This is not a sig.
    154. Re:One person's myth is another person's fact. by xouumalperxe · · Score: 1

      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.

      Except the article doesn't say comments are bad. It says bad comments are bad -- about as bad as no comments at all.

    155. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 1, Insightful

      What did this blog writer actually ever do that's worth a shit? Shouldn't that be one of the first things mentioned?

      Maybe some of us prefer to judge an argument on its merits, rather than whether we like the person who made it.

    156. Re:One person's myth is another person's fact. by jgrahn · · Score: 1

      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.

      I agree. But then there's the other extreme, where you're supposed to write code for the least common denominator. Like not use any "advanced" language features, in case a novice will stumble across the code and not immediately understand it.

      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.

      If that's not something which "implies a level of insecurity", then what is? It's much better than keeping silent and hoping noone notices the fart smell -- lots of people do that. I admit that it's sometimes not enough, and when it isn't the reader has a right to be pissed off ... but IME usually the ugliness is so obvious that nothing more needs to be said.

    157. Re:One person's myth is another person's fact. by jgrahn · · Score: 1

      On all machines I've coded for the right-shift on signed numbers have always been arithmetic. While not being a standard it is recommended C, and applies to atleast x86 and PowerPC.

      Recommended by *you*, you mean. *I* recommend staying away from undefined, obscure arithmetics in C as much as possible. You'll get into enough trouble as it is, without having to memorize not only the language, but also the workings of your particular set of target CPUs and compilers.

    158. Re:One person's myth is another person's fact. by Anonymous Coward · · Score: 0

      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

      That's only true across filesystems, a move within a filesystem essentially just renames the file.

    159. Re:One person's myth is another person's fact. by Bill+Dog · · Score: 1

      Just an off-topic but slightly amusing observation: I noticed that you are shown as a "Friend of a Friend" w.r.t. me, so being just curious I went to see which user(s) are serving as that link. Wouldn'tcha know, it's someone with the username "Doesn't_Comment_Code"!

      --
      Attention zealots and haters: 00100 00100
    160. Re:One person's myth is another person's fact. by whizzter · · Score: 1

      Could you give a reference on this? Partial register stalls on al->ax->eax writing is kinda obvious but this would only apply if you read after a partial write, doing a full register write would remove any partial stalls.

      In an analogy to that the partial writing of a the flags shouldn't matter unless you depend on it from an immediate flag reading instruction like a conditional branch or treating flags like numbers (ie pushf,etc). Especially since a shift would likely to be followed by a compare the shifts flag state is irrelevant for the one who reads the flags as it has been overwritten.

    161. Re:One person's myth is another person's fact. by b4dc0d3r · · Score: 1

      I could have rephrased a bit, but I clearly stated it was my opinion, based on the previous comment.

      "comments like that are absolutely useless" was exactly my conclusion. You can't think I was serious that "I have to stop working on this so I can finish my commenting before peer review so we can meet the deadline" is a reasonable comment, it just reflects the thought behind the actual comment. Useless "fixme" comments are, in general, not ok, and if you re-read with that in mind, I think you'll see that was my intended conclusion. Sometimes, like end-of-day in-progress commits, however, you get these kinds of "notes to self." Depending on what you're paying me, when the clock says go home I go home - there's a whole world of work-life balance that companies are picking up that encourages balance - stay when it's needed, otherwise make a mental (or otherwise) note and pick up tomorrow.

      It takes time and money to maintain documentation, whether it's a comment or design doc. You asked what my point is but you clearly stated it - it takes time and money. That means you have to have time in your schedule specifically allocated for documentation, or else you get whatever is present. If you don't set aside time for it, you'll get what people have time for, at most. I've never seen a schedule with time allocated for that, nor for post-deployment cleanup. Once you have a product that builds and passes testing, every coder knows it's not finished yet, but managers don't seem to get it. You need to clean up here and there, even if it's just deleting files left over when you narrowed the scope. Ensuring documentation is correct should be part of that task, especially if you limit changes to only comments, so that the binary output is identical (except for the compiler-embedded timestamp or other build-specific data). If the output is identical, and a diff can show only comments were changed, minimal re-testing needs done. Before you interrupt with "you don't test until the code is complete" - any defect found and fixed during testing might require complete re-testing anyway, so it's a good idea to have this planned for. If you don't have any re-testing to do, you're ahead of schedule.

      So I can summarize by saying, to gp, as long as you dedicate time for it you can require whatever you want from your employees, but expect high turnover rates unless your interview makes clear how stubborn you will be.

      External design documents are needed to indicate how everything works together - this information should not be in code comments. Especially when most languages can have usage mapped automatically. "Here's what this function does, and what the side effects are" is the type of comment that should be in place, but gp doesn't specify. It's a knee-jerk response, and probably a troll in retrospect. If you're going to be absolute in anything, you're going to be wrong in a lot of cases, and anyone with any experience should know this.

      Let me rephrase in the following way, the type and level of detail of comments depends on a lot of factors:

      Consider your audience when writing anything that isn't direct code (including macros or #defines or similar).
      Consider your conscience when writing anything that IS code.
      Will your code be taken over by a peer or client?
      Is this a temporary commit of in-progress code, or the complete document?
      Are you describing functionality which can be auto-generated by something like doxygen?
      Is the functionality you are commenting something simple, covered by first or second year CS courses?
      Is your manager going to fire you for simply leaving out a comment where the above suggests it is not necessary?

      One of those lines is out of place, but it summarizes gp's perspective. Hint, it's the last one. The whole point of the linked article is that some people have these notions burned into their brains exactly like gp posts - comment everything or you're fired. In fact, it is so contrarian that I am surprised I didn't initially dismiss it as an outright troll instantly.

    162. Re:One person's myth is another person's fact. by b4dc0d3r · · Score: 1

      "The programmer obviously has some reason for being unhappy with the code."

      Yes, but the programmer may not be able to describe it for various reasons. Too complicated to explain, too large to fit in the margin, code doesn't match accepted best-practices but I had to finish in time, or "I'm sure I could do this better, just not sure how right now."

      That last one is what usually happens for those "fixme" type quickies. Being unhappy with something and being able to describe it are different things entirely. Especially if you're off-shored help with a language barrier.

      What's absurd is expecting that every coder has the linguistic abilities comparable to their coding prowess. Lots of coders have no idea how to communicate in writing. If you've never seen an incomprehensible comment, or one that confuses the code more than clarifies, you're lucky.

    163. Re:One person's myth is another person's fact. by b4dc0d3r · · Score: 1

      Any software can be figured out, but I don't expect that it happen all the time. I clearly stated that certain comments are necessary, and even when comments are missing you have everything you need to figure it out. gp's point was "the code is unmaintainable because it has no comments and needs to be rewritten." My counterpoint was to call bullcrap. Context is important in this case, especially with a long-winded response like mine.

      Perhaps I wasn't clear - I've seen way too many comments from CS teachers or in language books to the effect that comments help remind you what you were thinking at the time. Usually it's the "code I haven't touched in a year and then I want to make a change but couldn't make sense of what I wrote" parable. Assembly books are the worst at this, which is funny because the only thing you lose by compiling and disassembling is variable and function/location names. Comments obviously as well, but if you wrote a function you should be able to read it.

      You learn things, and your style changes, and what you did last time doesn't seem like the best way anymore. I can buy that. If you can't make sense of your own code later on, you obviously are better now at what you're doing. You're also terrible at reading code and need to get better.

    164. Re:One person's myth is another person's fact. by b4dc0d3r · · Score: 1

      Based on the other supporting evidence, and the content of the comment, however, I think my conclusion is justified.

    165. Re:One person's myth is another person's fact. by Dom2 · · Score: 1

      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.

      Which is absolutely fine, just so long as you explained why in the next sentence. Or preferably three. As somebody above mentioned, comments should explain the why, not the how.

      Much like commit messages, but that's a rant for another day

    166. Re:One person's myth is another person's fact. by cheesybagel · · Score: 1
      I guess you never have programmed anything with a deadline. Even when there are no deadlines, often it is necessary to write a mockup which implements the required functionality. This can be to see how it can be implemented, or just to prove that it can be done. This mockup may or may not be reimplemented later.

      It seems really naive to me, the expectation by some people that we should all write code to the highest standard in the first iteration. The truth is no piece of software is ever complete. It is only complete when you decide not to spend any more time and resources on it. There is always one more feature you could add, or piece of code you could optimize, write in a cleaner fashion, or whatever.

      I can think of several pieces of code I had to write which were like 10 liners but would require several pages of documentation to explain the design tradeoffs involved. That is the order of complexity we are talking about here. Usually I add a short sentence as a summary, but sometimes this is not possible.

    167. Re:One person's myth is another person's fact. by honkycat · · Score: 1

      I've programmed with a deadline many, many times. I don't see what a deadline has to do with anything.

      So somehow you wrote these 10 lines of code that require a complex explanation. That's fine. Somehow you figured out how to do them. If you're working in a professional environment, I presume you figured this out in a notebook or some record of your process that can be preserved. There's nothing wrong with a comment that says "This is complicated, see notebook #n pg x for details" or some other indirect reference to how you figured it out in the first place.

      But really, you (and others) seem to be going to ridiculous extremes to justify not being helpful in your comments. In the specific cases I'm thinking about, a programmer senses something is undesirable enough about his code that he's tempted to add "// this is a hack." There is absolutely no reasonable argument that being more helpful than this is EVER prohibitive. You do not have to write the multi-page tome you suggest to be helpful, just give the next coder a clue what you are talking about. Don't make him guess what aspect of your code is a hack. ESPECIALLY if it's a concise piece of code with a complex backstory you need to give him some context to start with. I'm not saying write a thesis, I'm just saying expand a line or two on WHAT ASPECT of your code is a hack, maybe how it's likely to fail, etc. I don't see any reasonable situation where someone would be thinking to themselves, "// this is a hack" without having the ability to give a two line explanation of why the think that.

    168. Re:One person's myth is another person's fact. by honkycat · · Score: 1

      Nothing I'm asking for demands linguistic prowess beyond basic capability of communicating. This is a prerequisite for effective programming in a group setting. I'm not suggesting a detailed design case study in the comments, I'm suggesting some hint about what to fix or refactor.

      "//fixme" is a worthless comment.

      "//fixme - this code doesn't scale" is fine

      "//fixme - hard coding string length here" is fine

      That's all I'm suggesting. A few words, maybe a couple lines in some cases, just enough to give a modicum of context. I really don't believe there is any circumstance where someone capable of producing usable code has any excuse not to at least be able to give some hint about why they don't like what they've done.

    169. Re:One person's myth is another person's fact. by haruharaharu · · Score: 1

      If you're using shifts instead of multiplies in this day and age you're an idiot. The compiler will be confused and unable to optimize around it and it's nonportable.

      --
      Reboot macht Frei.
    170. Re:One person's myth is another person's fact. by wzzzzrd · · Score: 1

      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.

      This. I always write these sorts of comments on quick hacks of my own, because I HATE it when I stumble upon undocumented code which is obviously a quick fix ignoring all exceptional cases. If you found out after a hard time of debugging a 480 line function; consisting of nested ifs containing complicated math and reference pointers pointing to god-knows-what... The reason was a probable division by zero on the 4th level (*1), you start thinking: The original author(*2) of this code KNEW this (or at least could find it out after analyzing her code for ten minutes) and COULD WRITE IT IN THE COMMENT. Best side effect: While writing a comment like this, you sometimes think about your code and find a cleaner solution in no time.

      And by the way, if you simply recognize comments as part of the code, all the math of the GP concerning costs become false.

      (*1) I know it's bad software design. But this is about MAINTAINING code, not software design.

      (*2) It's like in literature: there are authors and writers, while in software development you have authors and programmers. Authors just do stuff, programmers just do stuff and have an ample mindset/ background/ mental condition thus delivering better quality.

      --
      On second thought, let's not go to Camelot. It is a silly place.
  2. No Comment by Anonymous Coward · · Score: 5, Funny

    No Comment

    1. Re:No Comment by Anonymous Coward · · Score: 0

      Microsoft is a great example of why commenting code is a good idea

    2. Re:No Comment by Zorlon · · Score: 1

      print "DEBUG: This is not a comment\n";

      --
      - Things are the way they are because they're coded that way -
    3. Re:No Comment by Anonymous Coward · · Score: 0

      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 Anonymous Coward · · Score: 1, Insightful

      This is absolutely true and even how becomes more important with lower-level languages where the code probably will not imply the intended outcome. Try figuring out clever assembly code without a running commentary; it's not fun.

    2. 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
    3. 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
    4. Re:Cliche, but true... by Nerdfest · · Score: 1

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

    5. Re:Cliche, but true... by PakProtector · · Score: 1

      C is a high level language. Anything more complex is balderdash and chicanery.

      --

      Edward@Tomato - /home/Edward/ man woman
      man: no entry for woman in the manual.
      "Qua!?"

    6. Re:Cliche, but true... by Drethon · · Score: 0

      Agreed, the problem with many comments is they try to explain how or even what instead of why. Explaining how or particularly what often just duplicates what the code explains to a skilled programmer (this works as long as the code isn't too obscure).

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

    8. 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'!"
    9. 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.

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

      Right there.

      Intent.

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

    11. Re:Cliche, but true... by master_p · · Score: 1

      I agree. But some times it is very hard to tell the 'how' from the code, so comments are required to tell the 'how'. I'd rather read English than code anyway.

    12. Re:Cliche, but true... by Hurricane78 · · Score: 1

      And Haskell code tells you what. The compiler figures out the how.

      Now all we need is a compiler that takes a motivation (the why) and automatically figures out the what and how. :)
      Is there such a thing, by any chance?

      --
      Any sufficiently advanced intelligence is indistinguishable from stupidity.
    13. Re:Cliche, but true... by deek · · Score: 1

      I completely agree. I always throw in simple one or two line comments before sections of relatively complex code. The reader can then immediately understand what the intent of that section is.

      Still, kudos to the author for challenging an idea that people don't often question. There is such a thing called over-commenting. It is not a good thing. Comments for the sake of comments are near useless.

    14. Re:Cliche, but true... by Anonymous Coward · · Score: 0

      You, sir, are a God.

    15. Re:Cliche, but true... by brausch · · Score: 1

      Absolutely correct. The "what" can always be figured out by reading code; the "why" has to be deduced unless it is explained.

      Just my opinion: the "why" can be best expressed as comments at the block or function level.

      --
      "Almost every wise saying has an opposite one, no less wise, to balance it." - George Santayana
    16. Re:Cliche, but true... by Anonymous Coward · · Score: 0

      Actually some people do find reverse engineering fun, which is nearly always what you need to do to understand uncommented assembler. Of course these people are freaks and should be avoided due to their questionable personal hygiene issues.

    17. Re:Cliche, but true... by hughperkins · · Score: 1

      Yes, also: if some intern was fixing a problem with your code, and they were sitting next to you, what sort of things would you have to explain to them in order for them to understand and fix your code, and not just dis' it to their boss and tell their boss what a load of crap your code is?

      I often imagine I'm explaining to an intern how the code works when I write my comments. I assume they understand the language, the libraries and stuff - they can just Google that stuff - but what does this class do? why? Target audience.

      The other possible target audience is myself in a year's time.

      To be honest, the longer I code, the more these target audiences converge on writing the same set of comments ;-) since I've learned how much one forgets when one comes back to the same code two years later.

    18. 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++ ?

    19. Re:Cliche, but true... by Anonymous Coward · · Score: 0

      This, too, is tautology that should be filed under misconceptions.

      A comment is just a semantic assist for the human worker. A good comment above the function often is just a translation of the code to English.
      Some programming languages are denser than English -- like poetry. There you have a problem with comments, and probably omit them
      except in particularly tricky cases. The people who cannot read such "poetry" (and there are many) have no business programming it (but they
      are sure to try all the same, sadly). This is not an elitist attitude, merely an observation that programmers come in various capacities and with
      varying degrees of experience. In fact, this is why one should be wary of the "WHY" comments: those comments seem to target the fumbling
      beginner who cannot put one and one together without help. You could dedicate full comment sections to detail the "big picture" or how the bits
      fit together, what invariants hold, etc., but this would fall under documentation or developer notes, then.

      In any case, every "why" can be written as a simple statement of fact (except the comments that are, in fact, in error).

    20. Re:Cliche, but true... by SecurityGuy · · Score: 1

      I like this. Another of my reasons for wanting comments is similarly simple.

      So-called self-documenting code tells you what it does. Comments tell you what it's supposed to do. Unless the developer never makes errors, those things are not always the same.

    21. Re:Cliche, but true... by Anonymous Coward · · Score: 0

      Javadoc, cod++ and anything similar also needs to be removed, simplified, or changed.

    22. Re:Cliche, but true... by dkf · · Score: 1

      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++ ?

      They're still not helping. What you want from comments is that which is not obvious by reading the non-comment parts of the source code or which could be got from the source but only with a lot of effort. Sometimes I'll put pseudocode in a comment to show what I started out with when designing a function (before it got obscured with lots of error handling special cases). Like that it acts as a map to understanding the function implementation.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    23. 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.

    24. Re:Cliche, but true... by Eudial · · Score: 1

      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++ ?

      That makes no sense at all. Javadoc et. al. can scrape that information from the code itself, and typically does a far better job at maintaining the information up to date.

      --
      GAAH! MY PRINTER IS ON FIRE!!! PUT IT OUT! PUT IT OUT!
    25. Re:Cliche, but true... by SharpFang · · Score: 1

      Have you tried to get any valid information from documentation generated by such a system?
      There are few more frustrating exercises than browsing through 50 different documentations of functions that describe exactly what you see and nothing what you want to know.

      The whole difference is between: /* Method name: setMode(mode)
      sets Mode;
      Returns: status
      */

      and /* Method name: setMode(mode)
      sets mode, 1 for verbose, 2 for debug, 0 for standard, -1 for heuristic=fast but inaccurate.
      Returns: 0 on success, 1-4 code errors, see @error_code for values.
      */

      The first one is not intended for javadoc, it's intended for developers to edit and make the second one out of it. The fact Javadoc will swallow it ok and generate a valid documentation out of it is a design error, not a feature.

      --
      45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
    26. Re:Cliche, but true... by 192939495969798999 · · Score: 1

      A design document tells you why. Using comments as your design document is like writing on each part of the car a reason why that particular part is there. Sure, it's a bit useful, but wouldn't it be easier to just see the design of a piston without having to take the engine apart?

      --
      stuff |
    27. Re:Cliche, but true... by Anonymous Coward · · Score: 0

      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++ ?

      You do realize the those typse of comments are selfgenerating in a good programming language's doc system?

      Didn't see I have to do this in Python for example - this information gets generated when I look into it with pydoc or some more sophisticated documentation tool.

    28. Re:Cliche, but true... by cheesybagel · · Score: 1

      It gets even more ridiculous. Most Java IDEs autogenerate the Javadoc headers and quite often the programmers do not bother to edit them!

    29. Re:Cliche, but true... by Anonymous Coward · · Score: 0

      javadoc will create that measly level of documentation through code inspection alone. In his particular example, the comment is pretty pointless.

  4. Over documentation is good by nurb432 · · Score: 1

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

    Having to decode your thought processes places extra a burden on the 'next generation'

    --
    ---- Booth was a patriot ----
    1. 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.
    2. Re:Over documentation is good by Anonymous Coward · · Score: 0

      God yes....

      A system I work with now has 29 serial links (modbus) to various places... the links and bus registers etc in external devices are ONLY documented in the header files of the C code used on embedded controllers...

      Trying to now virtualize this fecking mess is a major pain in the ass as we have to sit digging through header files and make maps of registers in use by hand... By hand because the code format is not at all consistent, neither is naming convention...
      Writing a parser turned out to be a waste of time since the header format will never be used again. *sigh*

      Kill me....

      Oh, and the code has been updated but not the comments so you have gems like
      a = 30913; // register 40914

      etc... kill meeeeee

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

    4. Re:Over documentation is good by rainmaestro · · Score: 1

      Suuuure it is.

      I was on a project a few years ago that required *every* non-whitespaced line of code to be documented. We would have functions that looked like this (in pseudocode)

      #Function Name: FindEntryID
      #Author: John Smith
      #Modified Date: 03/17/2006
      #Description: Find matching entry in the list and return the entry ID
      def FindEntryID(entry, list) #Function Declaration
      { #Begin Function
          for item in list #Loop through list
          { #Begin Loop
              if item.data == entry #If item data matches the desired entry
                  return item.id #return the ID
          } #End Loop
      } #End Function

      After a while, the entire team rebelled and gave management two choices: change the policy to something sensible or we *all* walk.

      Excessive documentation doesn't help anyone. Document fixes, document weird quirks, document the mission-critical stuff. But for god's sake, don't document basic loops, get/set methods, etc.

    5. Re:Over documentation is good by keeboo · · Score: 1

      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.

      I see no problem with clever code, as long as:
      1) there's a real benefit (usually speed),
      2) that part being modular and
      3) its behavior being well commented.

      IMO some of the "clever tricks" problems are:
      1) people overoptimizing code that didn't had much impact in the first place,
      2) people doing unnecessary (or even incorrect) optimizations the compiler takes care of (like (! a) instead of (a == 0), or (! some_pointer) instead of (some_pointer == NULL)),
      3) people adding tons of mutual dependencies for some (supposed) gain in speed and
      4) people who do "optimizations" which do not affect (or barely do) the performance, and the only thing it does is to make the source code tiny and "oh-so-clever" but hard to read and explosive once changes are made.

    6. Re:Over documentation is good by ps2os2 · · Score: 0

      The code that I found most baffling to debug was when the program modified itself to do different things.

      I asked that any self modified code be done away with and got a blank expression from the boss. I lead him to a room that had lots of chalk board space and explained very carefully with the black boards what self modifiable code was. Then I took a piece of code that was run in daily production and stepped him through it. It took 2 hours of explaining what it was before he finally came to the conclusion its a nightmare. He went up and tried to explain it to his boss and he could not, so I was summoned into the VP's off to re-explain it. This time it took three hours and I finally got through to these people that self modifying code is BAD. About two weeks later the edict came down to identify such code and do a write up on it and they hired some consultants to get rid of the code.

    7. Re:Over documentation is good by Anonymous Coward · · Score: 0

      5 years? Man, I've done that after a few weeks.

    8. Re:Over documentation is good by am+2k · · Score: 1

      Management actually caring about code quality? On what planet is your company located and how do I get there?

    9. Re:Over documentation is good by ps2os2 · · Score: 0

      They were a bank and they did pinch penny's.
      Another (not Y2K related) we had a machine that read the bottom of the check (MICR). The timing was incredible as you were allowed x many micro seconds before you had to tell the machine which pockets to put the check you had just read. The routine had to be extremely tight code. We had a few books open trying to come up with the shortest instructions to make the decision. We worked on this for at least a week (this was in the early 70's. It was hard but fun as you really had to do a lot of work to get the absolutely best optimized to make decisions fast.
      The point of this was that most code (especially the above item) had to be fast for two reasons. 1. Timing issues 2. Cost of processing.

    10. Re:Over documentation is good by belroth · · Score: 1
      I find it useful if the comments actually say something useful. I worked on a project where 90%+ lines of code were comments, 90% of the comments were commented out lines of old code, often several versions one above the other with the current line at the bottom. The rest of the comments were no better, I ended up writing a macro to delete all the comments from the code before I saw it. The programmers responsible for it are still doing it even with a code versionning system to tell them what's change form the earlier versions. Insane.

      Comments should be helpful but always treated with caution, even why comments can get out of date...

      --
      I hereby inform you that I have NOT been required to provide any decryption keys.
    11. Re:Over documentation is good by Anonymous Coward · · Score: 0

      5) people thinking they know C when they don't.

      (!a) is completely idiomatic C and you will see it on all influential pieces of code.

    12. Re:Over documentation is good by SharpFang · · Score: 1

      I got a slightly different approach. I document in second reading. If it took me more than a minute to recall what/how/why a section of my code does, I comment it as soon as I recall what/how/whu it does that.
      The downside is 2 or 3 pieces of my code I haven't managed to reverse-engineer till this day.

      --
      45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
    13. Re:Over documentation is good by Anonymous Coward · · Score: 0

      I've had the opposite experience after revisiting my own code after 10 years: "Wow what a smart programmer wrote this. Did I really write this? I am impressed!". But that was at a time when I could spent days perfecting the code.

    14. Re:Over documentation is good by dcam · · Score: 1

      I regularly get that on code I've written under 6 months ago. Often the problem isn't the code, it just isn't as clear to me as it was 6 months ago. It might make sense now, but will it in 6 months, 1 year, more?

      --
      meh
  5. 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 MichaelSmith · · Score: 1, Informative

      I would rather
      rewrite it than try to decipher it.

      In the environment I work somebody will try to import your change later and they will want to know why you made that change. They aren't going to be very impressed if your answer is that you couldn't understand the original code. By making that change you would be creating work for a lot of other people down the chain.

    2. 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
    3. 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
    4. 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.

    5. 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"
    6. Re:Wrong on all accounts by Anonymous Coward · · Score: 0

      They can suck my sweaty balls.

      Some asshat believes he is too good to comment his code? I don't have the time to waste deciphering his spaghetti rats nest of global variables and copy/paste flow control.

    7. Re:Wrong on all accounts by Anonymous Coward · · Score: 0

      Job security

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

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

    10. Re:Wrong on all accounts by MojoRilla · · Score: 1, Interesting

      As time goes on, comments become either lies or damn lies. They almost never are kept up to date with the source, and they also contain programmer misconceptions. The only truth is the source code.

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

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

    13. Re:Wrong on all accounts by rainmaestro · · Score: 1

      Undocumented code is only a problem if the code does something that isn't obvious to any second-year CS student. Some code simply doesn't require comments because the code is obvious to anyone reading it.

      Get/Set methods: do they *really* need comments?
      Basic assignment loops?
      List traversal loops?
      Swap function?
      etc, etc

      That being said, poorly or incorrectly documented code is truly evil, I'd rather see no comments than incorrect comments.

    14. Re:Wrong on all accounts by rainmaestro · · Score: 1

      Does a swap function really need any comments? Yes, I know we have std::swap, but I still see people rolling their own anyway.

      Okay, if you're doing some fancy XOR'ing to avoid creating a temp variable, maybe. But your basic t=a, a=b, b=t function shouldn't require any comments, even at the function level.

    15. Re:Wrong on all accounts by digitig · · Score: 1

      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.

      Solution: rigorous peer review.

      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.

      Solution: rigorous peer review.

      --
      Quidnam Latine loqui modo coepi?
    16. Re:Wrong on all accounts by Gothmolly · · Score: 1

      And you're not as perfect as you think you are.

      Welcome to reality.

      --
      I want to delete my account but Slashdot doesn't allow it.
    17. Re:Wrong on all accounts by b4dc0d3r · · Score: 1

      I translated your comment in the following manner: There is not, and never will be, a single generic resolution for arguments such as this. In this case there is no question, yet people are giving answers. This blog post did not say "Should we or should we not comment our code." A generic guideline such as that suggested by the blog author should be tailored to the environment, based on the workflow and expectations. Take a stranger's advice with a grain of salt, in other words, because you are just as strange to him as he is to you.

      So then people post rants about how they've seen badly commented code, or completely without comments, or that they don't comment things that should be obvious and everyone has a soapbox. The original intent of the blog post was, as I understand it, to remind people of the importance of keeping your code in good order - in this case by including comments where needed, and excluding where not needed. Seems fairly simple, but here we are with hundreds of comments. Le sigh.

      Rewriting a core GNU tool function because you don't understand it simply will not happen at this point - too many downstream distro maintainers will simply bypass the work. If you're the lone gun on inherited code, rewriting it is probably a lot more justifiable. If you're the app owner and lead dev, and no one else uses your code (except maybe unmodified) you can do as you please. In fact, under these scenarios, the degree of commenting required is going to be different. If you write your own code for yourself, you might not need comments. If you intend to maybe someday release the source, you might need to comment things that seem obvious to you.

      I don't understand the confusion here, unless people are just taking advantage of the opportunity to vent here instead of at their own jobs, where it would do more good. What would happen if everyone who commented read every single 0-or-above comment? Would opinions change?

    18. Re:Wrong on all accounts by leehwtsohg · · Score: 1

      Which is even more true for self-commenting code. It is easy to update comments, a bit harder to change the name of a variable throughout the whole program.

      #define TWO (3.4)

    19. Re:Wrong on all accounts by Thing+1 · · Score: 1

      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.

      It sounds like you would prefer unit tests that function, in place of comments.

      I don't disagree -- although useful comments would be a helpful addition...

      --
      I feel fantastic, and I'm still alive.
    20. Re:Wrong on all accounts by Anonymous Coward · · Score: 0

      I'm the guy with half the staff required to do the minimum job, while the "comments are god" guy in the office has twice as many as he needs.

      If you ever work for me I will personally fire you, or worse, you can go work for Sean - he's a fuck.

      Comments are good, but to hell if you think that commenting the following is useful.

      My appologies for being a mix of many languages in one litlte psedocode comment.

      int ProcessRecords(Records &recs) // if there aren't any records to process exit
      if(recs.length()==0)
              return;
      else // records to process, process them!
              foreach record in recs
                      ProcessRecords(record);
              endforeach
      endif

             

    21. Re:Wrong on all accounts by jhol13 · · Score: 1

      The only truth is the source code.

      Up to the point where the program is run first time ... and a defect is found.

    22. Re:Wrong on all accounts by grimw · · Score: 1

      You really have all that experience and need all that commenting? I think you need to check your experience at the door. Hell, I've got "two years real world experience outside school", and no one comments their code where I work, including me. I would hardly call them unprofessional or bad programmers, even if occasional things do pop up that seem, and may be, retarded, because it's almost always a big waste of time. After looking at code like that for over two years, across several projects in several languages, I can say it's not as hard to read uncommented code as you make it out to be. In fact, I often skip reading comments for the sheer fact that they're usually incorrect because they're either not maintained as the code is updated or were always wrong.

      Except for some extremely obscure pieces of code, generally revolving around optimizations, architecture-specific workarounds, compiler-bug workarounds, etc., have I ever found comments to be useful outside of documenting an API. In point of fact, there will never be a comment stating more correctly what the code is doing than the code itself.

      As one caveat, I've seen good use of comments in ASM. However, with the ability to use more advanced assembler features in GCC or LLVM these days, you can put pretty sophisticated names on your code-flow elements and not require nearly as many comments as in the past. And with being able to inline ASM into code for those cases you need it, you can even use sophisticated meta-names for your registers that are obvious to the reader. Also, being the fact that the only person that work on an optimized piece of code would be someone that already knows that architecture's ASM or can learn what they need, you can rest assured that they'll have all the tools necessary to read and modify your code.

    23. Re:Wrong on all accounts by grimw · · Score: 1

      I should say that one area where we do keep updated documents are outside the code. They're in the form of requirements documents and high-level component overviews with the general idea behind them. This has always been enough for my colleagues and me to get a good grasp of what the code is doing when we encounter it. Still... we don't comment the code itself.

    24. Re:Wrong on all accounts by obarthelemy · · Score: 1

      I think commenting is a communication, rather than technical, skill. Some programmers may not be skilled at it, others better, independently of their programming skills. It requires being able to empathize with the reader, and pedagogy.

      --
      The Cloud - because you don't care if your apps and data are up in the air.
    25. Re:Wrong on all accounts by Anonymous Coward · · Score: 0

      Up to the point where the program is run first time ... and a defect is found.

      But the code always does what it was written to do.

    26. Re:Wrong on all accounts by Anonymous Coward · · Score: 0

      I'd like to add that comments that just reiterate what the code does can be quite helpful for debugging though, if they don't match the code that usually means that
      a) Whoever wrote it didn't know what they are doing
      b) The code was changed rather carelessly
      That usually indicates a good point to start bug-fixing.
      However that means that the code by itself must be clear enough that at least the clever programmers can understand it easily enough not to be tempted to just believe the comment.
      No amount of comments is a substitute for good code (however some of those "every line must be commented" rules seem to assume that).

    27. Re:Wrong on all accounts by Anonymous Coward · · Score: 0

      Sometimes code is not poorly written, just because it needs deciphering.

      I've seen cases where the understandable code is so slow, that the users waste a lot of time, while the code that is not understandable, takes less than a second to execute. In this case, comments are really useful.

      I have also seen situations where the unreadable code is marginally faster, but that little difference, is the make it or break it.

    28. Re:Wrong on all accounts by Rockoon · · Score: 1

      ..and there are plenty of reasons to write your own versions of what are otherwise simple standard library functions. The xor swap is a good example, but also things like sorting come to mind.

      Sure, that standard library sort is a good general purpose sort but thats also its weakness.. you can literally always do it faster (often significantly.. really), or always require less memory overhead (as little as zero)

      I comment my data. The code is just the interactions between the data. Adding new interactions does not require that old interactions be documented.. it requires that the data be documented.

      --
      "His name was James Damore."
    29. Re:Wrong on all accounts by paenguin · · Score: 1

      My code is as good as I think it is. Your comprehension skills are not as good as you think they are.

      --
      We should start referring to processes which run in the background by their correct technical name... paenguins.
    30. Re:Wrong on all accounts by fishexe · · Score: 1

      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.

      Having read Slashdot for many years, all I can say is poorly formatted and prematurely line-fed text is unprofessional and I would rather rewrite it than try to look at it. You haven't yet given any excuses for it, but all I'll say to you when you do is: "Your comment is not as good as you think it is."

      --
      "I don't care about the Constitution!" --Bill O'Reilly, November 17, 2009
    31. Re:Wrong on all accounts by fishexe · · Score: 1

      His point is that worthless comments are worse than no comments at all.

      Unfortunately a large percentage of the comments you see on Slashdot today were autogenerated by monkeys and are just noise.

      --
      "I don't care about the Constitution!" --Bill O'Reilly, November 17, 2009
    32. Re:Wrong on all accounts by johanatan · · Score: 1

      I agree. I read a lot of code and if the quality is such that you'd want to keep it, comments are only needed when something is non-obvious (e.g., when equations or data from an external source are encoded).

    33. Re:Wrong on all accounts by alanmusician · · Score: 1

      Yes, and it is no coincidence that those who write unreadable code also write unreadable comments. I notice that the more I progressed in programming skill, the less I made comments because I found myself stating the obvious.

      When I look back over an old horrible VB program I had to take over maintenance of for awhile I notice that I left quite a few comments of both my changes and existing code, but that most of those comments were just about as esoteric as the code. It's hard to clearly explain the logic behind a twisted mess.

      Whenever I review the comments in my latest project I find that there are few and most of them are meta-comments that describe the use of generic objects, typically notes on the business logic, not technical notes.

  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 Anonymous Coward · · Score: 0

      Bonus points to the people who write their comments in clear grammatically correct prose.

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

      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.

      // TODO: Implement mathematically optimal commenting

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

    4. Re:Has No One Actually Studied This? by jbolden · · Score: 1

      Actually there have been tests. The problem they are very specific to platform / language / development techniques in vogue. For example the whole hungarian variables debates from 20 years ago.

    5. Re:Has No One Actually Studied This? by Anonymous Coward · · Score: 0

      "they found that in general the more comments in the code, the more problems were reported against it."

      I wonder which of these is cause, and which effect. It could just be that the difficult code has more problems, sees more revisions, and hence, accumulates more comments.

    6. 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.
    7. Re:Has No One Actually Studied This? by gadzook33 · · Score: 1

      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. If you abstract things well, it does seem to make for very readable code. Maybe I'm guilty of too much hubris regarding my own programming, but when I go back years later and read old code I usually find one of two things to be true: either I have trouble reading it and almost immediately see a better way of organizing it that would help. Or, I can read it just fine. But rarely do I find that comments make the difference. In my mind the argument is analogous to procedural documentation. 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? Don't explain what can simply be encoded and factored away. People who argue against tools like intellisense might as well be arguing against higher-level languages. Of course there has to be a balance, but these tools exist for a reason. We can't write in machine code from now until the end of time - we have to be more efficient and more productive than we were before.

    8. 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?
    9. Re:Has No One Actually Studied This? by Anonymous Coward · · Score: 0

      Shouldn't it have measured the comment-to-code ratio rather than the number of comments? More lines of code imply more comments, and more lines of code (generally) give a larger chance of something going wrong.

    10. Re:Has No One Actually Studied This? by Byzantine · · Score: 2, Informative

      Sounds sorta like literate programming.

    11. Re:Has No One Actually Studied This? by Anonymous Coward · · Score: 0

      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.

      This is a ridiculous statement. Depending on the implementation sometimes it is certainly nice to change data in place for performance reasons and to reduce potential mistakes in the copy (buffer overruns being an extreme example). However, sometimes maintaining two copies of data is crucial (i.e. current and previous states). When you see a copy block explaining what it is trying to do it is easy to figure out if it is actually doing that task correctly.

    12. Re:Has No One Actually Studied This? by Anonymous Coward · · Score: 0

      I know better than most of the complaints I read on here, and yet, I can't get a programming job. Eh, go figure.

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

    14. Re:Has No One Actually Studied This? by oliverthered · · Score: 1

      " noticed was their tendency to keep copying data from one data structure to another instead of using it in place"

      hmm.... maybe they just read the python tutorial on the python website.

      It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient:
      >>> for x in a[:]: # make a slice copy of the entire list ... if len(x) > 6: a.insert(0, x) ...
      >>> a

      far better solution would be to loop over a and build a list of thins you wanted to insert then loop over the things you wanted to insert list and modify a.

      immutable types are really for beginners and only case problems for people who actually can write code.

      --
      thank God the internet isn't a human right.
    15. Re:Has No One Actually Studied This? by Anonymous Coward · · Score: 0

      This is amusing: "when it finally becomes a real engineering discipline". Certainly there are plenty of people who think software engineering is a real engineering discipline, after all you can get a degree in software engineering. But then, there are just as many people (most of whom are in those other real engineering disciplines) who believe that SE is not real engineering.

      My point is: In those other real engineering disciplines engineers are expected to keep notebooks, write white papers, journal articles, or whatever is most convenient to document their work so other people can understand their design decisions. The luxury of having your notes stay with your design does exist as it does with a code file. You cannot write your design decisions in the silkscreen on a PCB, or the top metal layer of a chip, etc...

      In my undergrad engineering days keeping a lab notebook was a significant portion of the grade for that lab. And I know that in CompSci, SE, other programming classes, comments and good coding style are preached. Unfortunately those lessons are lost on most people in the classroom. It seems that keeping a lab notebook/commenting code are lessons that are best learned by the experience of not having done it and then realizing you should have.

      So comment your code, document your designs, and stop having asinine arguments like this, and then maybe the other real engineers will stop laughing at you.

    16. Re:Has No One Actually Studied This? by Anonymous Coward · · Score: 0

      Or maybe complicated areas that have the most potential for errors also require the most comments...

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

    18. Re:Has No One Actually Studied This? by malp · · Score: 0, Flamebait

      oh for fucks sake, no one but first year CS students talk about sort algorithms. I was accidentally assigned to the CS dorm freshman year. Christ, you woulda thought sort algorithms were the pinnacle of philosophy based on those #$#%#$%#%$ 's conversations.

    19. Re:Has No One Actually Studied This? by Anonymous Coward · · Score: 1, Insightful

      I think you may have the cart before the horse.
      Code which is doing a hard job, often needs more comments because there are more things to keep in mind when working on it. it is also more likely to have problems.

      I have been programming for more years than the age of a large portion of the readership of slashdot (34 years), and I can tell you that when you come across your own code twenty years later, you have NO IDEA about what you were thinking when you wrote it. After years of experience I have decided that code should be rejected if you can not tell what it should be doing AND WHY without actually looking at the code itself. The comments should form an independent summary of what the program should be doing, a bit like the "director's commentary" track on some DVDs.
      Think of them as an error recovery track.

      I recently started work at a new company and to my dismay found that much of the code was uncommented. I estimate it slowed down my understanding of how the product worked by several hundred percent. And yes, somewhere, you have used my code, whether you knew it or not.

    20. 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?
    21. Re:Has No One Actually Studied This? by Anonymous Coward · · Score: 0

      Yeah, sure. Messy code get fixes. Developper fixing a messy code add comments. Hence messy code have comments.

      Correlation != causality.

      And probably, half of the comments were: // Fix for #34212 // Fix for #41223

      etc, etc

  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
    /)
    1. Re:More verbose == less readable? by mpc92 · · Score: 1

      I find over and over that I'd rather have 10 simple lines over 1 tricky line for one simple reason: invariably one of the tricky actions holds the key to a bug, and I want to have more precise control over where my breakpoint is (which method call in the tricky line is throwing that null reference exception anyhow?).

    2. Re:More verbose == less readable? by buddyglass · · Score: 1

      And if you're that worried about a verbose section of code, extract a method, give it a good name, and be done.

      In total agreement here. Usually just look at a short-ish method's name, its parameters, and its return value, makes it clear what it does. This is different than if that same code were included in-place, since in that situation its not clear what the "inputs" and "outputs". Plus extracting it usually makes the section from which it was extracted easier to read.

    3. Re:More verbose == less readable? by pjt33 · · Score: 1

      Unless you're doing it for absolutely required performance reasons

      Or numerical reasons. Sometimes it happens that the 3-line version is algebraically equivalent to the 10-line version, but more stable numerically. In this case you may need to replace 3 lines of comments with 20 lines sketching the outline of the 10-line version and giving a proof of correctness of the 3-line version.

    4. Re:More verbose == less readable? by Kjella · · Score: 1

      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.

      And for the love of $deity, don't create side effects which aren't apparent from the function name. Like doing data hacks in the loadFromDisk() method. What is unfortunately also annoying with "functionifying" a method is that it clogs up the class methods, I wish there was a keyword like "foohelper() helps foo();" which would mean foohelper() is only in scope inside foo(). If something is complex and consists of several long operations, it's usually cleaner to have a supermethod which only calls helpers.

      --
      Live today, because you never know what tomorrow brings
    5. Re:More verbose == less readable? by itzdandy · · Score: 1

      efficient code should be to goal.

      I see a lot of sh script written with people using 'for' + 'ls' + 'grep' to find files, filter the output, and perform some action in a loop. This creates extra lines of code when some 'clever' one liner could do this better.

      in bash for example , declare everything you can so that your program doesnt have to wait on a $PATH return and search for your program. Learn each functions options so you dont stack things together for no good reason.

      this:
      FINDPATH=/here;
      PROGRAM=/usr/bin/touch;
      FINDFLAGS="-this -than -theother";
      find $FINDPATH $FINDFLAGS -name regex -exec $PROGRAM {} \;

      is about 1000 times faster than this:
      for x in `find / | grep -e regex`ldo program $x;done

    6. Re:More verbose == less readable? by jbolden · · Score: 1

      It depends on whether we are talking a one liner like Haskell or a one liner like Perl.

      Perl and C have an incredibly powerful syntax which allows for mashing programs down to one cool line of code. These techniques can be used for structuring the program to keep the emphasis where it should be.

      Conversely Haskell tends to make you think long and hard about the true nature of the problem. That one line represents a perfect understanding of the algorithm if it doesn't make absolute sense, in a "it could be no other way" you shouldn't be touching the code. The result is 3000 line programs become 60 lines of really interesting ideas.

    7. Re:More verbose == less readable? by MathiasRav · · Score: 1

      What is unfortunately also annoying with "functionifying" a method is that it clogs up the class methods, I wish there was a keyword like "foohelper() helps foo();" which would mean foohelper() is only in scope inside foo(). If something is complex and consists of several long operations, it's usually cleaner to have a supermethod which only calls helpers.

      Ideally, those methods/subroutines/functions, i.e. foohelper() should be declared and defined inside the method/sub/function they're helping, i.e. foo():

      function foo(input):
      function preprocess(input):
      ...
      end function function process(input): ... end function intermediary = preprocess(input) result = process(intermediary) return result end function

      There are two kinds of helper functions, those that serve only one function and those that are useful in general (which can also become a problem) - and if your helper function is only useful in one scope, it should only be defined in that scope.

    8. Re:More verbose == less readable? by MathiasRav · · Score: 1

      Damn, clicked Submit instead of Continue Editing. My point still stands.

    9. Re:More verbose == less readable? by Mad+Merlin · · Score: 1

      In the same vein, this:

      find $FINDPATH $FINDFLAGS -name regex -exec $PROGRAM {} +

      is about a thousand times faster than what you suggested:

      find $FINDPATH $FINDFLAGS -name regex -exec $PROGRAM {} \;

      At least in this case, as touch accepts an arbitrary number of arguments.

    10. Re:More verbose == less readable? by dcollins · · Score: 1

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

      This sounds like ideology taken too far. Why would one well-commented line inspire wrath? That doesn't make any sense.

      --
      We know where leadership by an anti-intellectual "strongman" who scapegoats minorities and likes boisterous rallies goes
    11. Re:More verbose == less readable? by Anonymous Coward · · Score: 1, Informative

      You'd have to document why you think all file names will fit on a single command line.
      There are probably file systems where all the file names together wouldn't even fit in RAM (admittedly the whole thing might take too long to run to be reasonable then, but it sure is a tradeoff, and I think that's a good example of something that needs documentation)

    12. Re:More verbose == less readable? by Cederic · · Score: 1

      Efficient code is fine, but what's the efficiency you're measuring?

      Efficient code writing? Efficient code maintenance? Efficient compilation times? Efficient code execution?

      Three of those cost a lot of money, yet many programmers focus on the fourth (and still cock it up).

      Of course, it's pretty easy to write the 4 line script you provided in a single line by explicitly stating the variables, but that's less re-usable :)

    13. Re:More verbose == less readable? by tanderson92 · · Score: 1

      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.

      Given your inability to properly subtract I think you've had performance problems not just in your code, but in school as well.

    14. Re:More verbose == less readable? by ninjagin · · Score: 1

      I used to do a lot of sh/ksh/perl scripting, and once I developed a little facility with sed and awk and regular expressions (not to mention 'eval', my all-time fave ksh function), I found that commenting these kinds of filters and parsing tricks was very helpful as I looked back at what I was doing. Keeping things short and sweet and efficient (if need be) is great, no question. Being able to hand what I wrote to someone else, or being able to revisit something years later and make sense of something without having to pick up a book to re-acquaint myself with the syntax rules, was a real time-saver. I'm a manager, now, but every now and again the guys on my team show me things I wrote and tell me how helpful those little notes were.

      --
      .. pa-ra-bo-la, pa-ra-bo-la, 2 pi R, 2 pi R, where's your latus rectum, where's your latus rectum, 2 pi R
    15. Re:More verbose == less readable? by Anonymous Coward · · Score: 0

      I have also felt the same. We use a horrible one, but do all debuggers fail to tell the exact method call that is throwing null ref exception ?

      Posting as AC to protect the identity of the company that forces a horrible IDE on us :(

    16. Re:More verbose == less readable? by Mad+Merlin · · Score: 1

      No you don't, because they don't all need to fit on one command line. Find will chunk them into chunks much larger than 1, but smaller than the command line length limit. Trust me, I've used find \; and find + on directories with more than half a million files in them.

    17. Re:More verbose == less readable? by bingoUV · · Score: 1

      What do you mean by numerically stable? If some code is algebraically equivalent to another code, both would produce the same result always, right?

      --
      Bingo Dictionary - Pragmatist, n. A myopic idealist.
    18. Re:More verbose == less readable? by nmb3000 · · Score: 1

      Given your inability to properly subtract I think you've had performance problems not just in your code, but in school as well.

      Uh, 10 original lines – one-liner – 3 comment lines = 6 fewer lines.

      Who did you say can't subtract?

      --
      "What do you despise? By this are you truly known." --Princess Irulan, Manual of Muad'Dib
      /)
    19. Re:More verbose == less readable? by Anonymous Coward · · Score: 0

      My apologies for being too lazy to not actually checking the documentation before making claims :-)

    20. Re:More verbose == less readable? by pjt33 · · Score: 1

      Not if you're using floating point numbers. Using 32-bit IEEE-754 floats,

      float accum = 0f;
      for (int i = 0; i < 10; i++) accum += 0.1f;

      leads to accum holding a value slightly larger than 1 (1 ulp larger).

      float accum = 10f * 0.1f;

      leads to accum holding exactly 1. That's a simple example of code which is algebraically equivalent but produces different results due to the limitations of floating point representation.

      As numerical instabilities go that's so small that arguably it doesn't count at all. On the other hand, once you throw in e.g. arcsin(accum) or sqrt(1 - accum) at the end it's the different between getting a result or a complaint that you've passed in an invalid argument.

    21. Re:More verbose == less readable? by bingoUV · · Score: 1

      Oh yes, you are right. Thanks. Long time since I got entangled in floating point arithmetic. I had also never heard of it being called numerical instability.

      --
      Bingo Dictionary - Pragmatist, n. A myopic idealist.
  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
    1. Re:In other news... by mewshi_nya · · Score: 1

      sentences linked into a meaning into a paragraph into a story! Brilliant!

      Actually, I really like this post. Someone, please mod this up.

      If more people wrote simpler code, it would be easier to read on my end, as a non-programmer

    2. Re:In other news... by Anonymous Coward · · Score: 0

      undocumented code is unprofessional.

      unprofessionals dont get hired often or keep their jobs for long.

      if you work for me, you document your code, cause unless specifically agreed to beforehand, your code is part of a product belonging to my company, and i will not be screwed over down the road cause you left, and the code is nigh undecipherable except by the one who wrote it.

    3. Re:In other news... by Anonymous Coward · · Score: 0

      People hate Stephen King? News.

    4. Re:In other news... by CAIMLAS · · Score: 1

      The irony is that I'm not a coder. I'm an (unemployed!) sysadmin. I hate coding, but I'm at least not a festooned idiot. :P

      --
      ~/ssh slashdot.org ssh: connect to host slashdot.org port 22: too many beers
    5. Re:In other news... by Anonymous Coward · · Score: 0

      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.

      Was this meant ironically?

  9. Blame my professor by Quila · · Score: 1

    I had excessive commenting drilled into me in college. It's one of the things I've had to unlearn.

    1. Re:Blame my professor by spiffmastercow · · Score: 1

      I was so put off by having to write more comments than code in college that I have a hard time forcing myself to comment.

  10. Comments are not design by Anonymous Coward · · Score: 1, Insightful

    Code that has concise, sensible comments is indicative of a good design. However, I don't care how 1337 you are, no professional developer worth a damn programs anything bigger than a 3-line batch without at least some sort of design document. Comments that relate back to the design document are one thing, but it is really hard to use comments to point out the design of a program which had no design other than "I am ok to just wing this because i am 1337."

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

    1. Re:Please no by MichaelSmith · · Score: 1

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

      Yeah there is this guy I have the misfortune to be working with. Once in a code review he insisted that all my code be double spaced (one blank line between every line) because he was having trouble reading it. I said why don't you configure your editor accordingly. He said in his team they do pair programming so every workstation has to be set up exactly the same way...

    2. Re:Please no by The_reformant · · Score: 1

      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.

      I can kind of understand this, often in the quest to make things more understandable things are refactered into methods/functions that arent modular operations in themselves which can lead to more confusion since they masquerade as pieces of modularly reusable code when they in fact rely on assumptions which happen to be satisfied by their caller.

      Its also worth noting that you do get a performance and memory usage penalty for pushing additional frames onto the stack. In certain cases that can be a factor. (As an aside why is it in Uni that recursive code is held in such high regard as being elegant whereas in day to day like its almost always a bad idea. I made that mistake a few times early on in my professional life).

      --
      I have discovered a truly remarkable sig which this post is too small to contain.
    3. Re:Please no by gnasher719 · · Score: 1

      Yeah there is this guy I have the misfortune to be working with. Once in a code review he insisted that all my code be double spaced (one blank line between every line) because he was having trouble reading it. I said why don't you configure your editor accordingly. He said in his team they do pair programming so every workstation has to be set up exactly the same way...

      The guy is completely illogical. Next you review some of his code, and you insist that all his code should be single spaced (no blank lines between lines of code) because you have trouble understanding the code if it doesn't fit on a single screen. What is he going to do then?

    4. Re:Please no by farnsworth · · Score: 1

      Christ, I know everyone has their own personal style and everything, but this is just pernicious.

      Every is entitled to their own personal style, but context is also very important.

      If you are writing a math-heavy algorithm in c, comments are crucial, both at the API level and within the implementation.

      On the other hand, if you are writing a webapp in c#, an organizational mandate to "document every public method and public class" can be a huge waste of time if not harmful.

      --

      There aint no pancake so thin it doesn't have two sides.

    5. Re:Please no by Anonymous Coward · · Score: 0

      This attitude is the same as the original post. 'my code is perfect and every should conform to what I do if you do not like it here are some hoops to jump thru to be like me'. The guy asked you to match what the rest of the team was doing and you came back with a snide remark. Instead of showing him why that style is 'worse'/'better'.

      The reason for doing these things is not always for yourself. It is for other people to help you out. Your not as good as you think you are. You are also not always around or will be around. I have dealt with programmers such as you many times. MANY times everyone else ends up fixing the mess you make. Then you turn around thinking they are all full of crap.

      I am a pretty good programmer. However, *THE* highest complement I ever get from other programmers is 'your code is easy to read and the comments are always spot on.' When writing code you are writing for 3 groups. 1) the compiler 2) yourself and 3) most important your team mates.

      For 1 you could write cryptic ass crap and the computer would figure it out.
      For 2 you could also write cryptic ass crap and you MIGHT figure out today but what about 2 months from now?
      For 3 you can NOT write cryptic ass crap. You *MUST* communicate to them what you are doing. If this means double spacing your code then so be it. BTW after 20 years of coding I have found double spacing is most readable. They help you make your code look good and easier to read. It looks 'funky' at first but you quickly come to like it. When its 2 in the morning and I have to tweak some code I do not want to have to worry about what options *YOU* were using in your editor and making my options match. You will have style fights and you will loose these battles, I have lost/won many. I have worked on projects where everyone did 1 style. Those projects were successful. I have also been on many projects where 'we are all professionals and write however we like' and those all failed. The reason they failed? The team was not a team it was a group of 'hot shots'. One of the first rules of my projects are 'use the style of the group or find another group'. This helps promote teamwork in a weird way. It also helps others quickly find bugs as the code will just 'look weird'. This is one of the most important tools you will to writing 'good' code. Do not throw it away because you think you are 'better' than everyone else.

    6. Re:Please no by Anonymous Coward · · Score: 1, Insightful

      A smart optimizer will inline where appropriate. Of course, relying on the optimizer is not always the right idea, but unless you know it is a problem, it is usually the right idea. Also, you can mark functions as inline in C (and probably other languages) if they are logically separate functions, but should not really be called as separate functions. Of course, as you note, separating out functions where the pre-conditions are very precise and non-obvious is going to cause maintainability headaches.

      On recursion, it is generally a much cleaner way to express an algorithm and easier to write proofs about. Also, if the function is tail-recursive (its recursive call's return value is always immediately returned), then even a very simple optimizer will always turn such a function into a loop as the transformation is trivial. Unfortunately, in the real world, tail-recursive functions aren't actually that common, especially as any error checking on the result nullifies the tail recursion assumption.

    7. Re:Please no by ChrisMaple · · Score: 1

      The first thing I do with source code with lots of white space is :g/^$/d. This occasionally lets me put what was once a 200 line file onto the screen all at once. If the code is well structured, the structure becomes evident; with many blank lines loops and blocks are hidden because they can't be seen all at once.

      It's so important to see everything at once that I often print out files and tape the pages together. Then I use colored pencils to show blocks and flow.

      If the group insists on double spacing, I can always run it through a sed script when I'm done.

      --
      Contribute to civilization: ari.aynrand.org/donate
    8. Re:Please no by owlstead · · Score: 1

      "(As an aside why is it in Uni that recursive code is held in such high regard as being elegant whereas in day to day like its almost always a bad idea. I made that mistake a few times early on in my professional life)."

      Oh, that one is easy. Recursive code is a nice mathematical concept, used a lot in functional programming. As computer science more or less evolved from mathematics (and maybe physics) there is a lot of influence from those fields. You'll probably see it a lot less in studies for applied software engineering.

      Yes, and it's something you *should* certainly avoid, even when the platform does not suffer easily from stack overflows. I normally try and replace it with a state machine (I think, nowadays recursive methods have somehow disappeared from all of my designs).

    9. Re:Please no by Anonymous Coward · · Score: 0

      void format_code_for_idiot()
      {
          char line[200];

          while( fgets( line, 200, stdin ) )
          {
              puts( line );
          }
      }

    10. Re:Please no by Anonymous Coward · · Score: 0

      when he thinks code is overcommented, he can ask Emacs to hide the comments.

      If he ignores the comments, then his changes will lead to discrepancies between the code and the comments. If comments exist, they must be maintained. Wrong comments are worse than no comments.

      Overly verbose and other types of unnecessary comments (i*=2; //multiply i by 2) are indeed bad and cause actual problems. Comments are their own kind of program and the more comments there are, the higher the chance that the comments "do" something different from what the code does.

    11. Re:Please no by Anonymous Coward · · Score: 0
      Change it to:

      - void format_code_for_idiot()

      + int format_code_for_idiot()

      {
      char line[200];

      while( fgets( line, 200, stdin ) )
      {
      puts( line );
      }

      + return (739);

      }

      It's fun! The idiot will spend the whole afternoon trying to figure it out!

    12. Re:Please no by Anonymous Coward · · Score: 0

      masquerade as pieces of modularly reusable code

      Where in fuck's name did you get the encephalitic idea that something being a function necessarily implies that it is reusable?!?

    13. Re:Please no by Anonymous Coward · · Score: 0

      "Self-documenting code" is probably an oxymoron. Code is how. Comments should be why. And what.

      Except in the most trivial and obvious cases, Code without comments is only half the program. Granted, it's the half that does the actual work, but if you want programs that are "write only", use APL. Or Perl.

  12. Lies or Wishful Thinking by KalvinB · · Score: 1

    Comments are useful if kept up to date with the code. Otherwise they turn into bald faced lies or wishful thinking.

    Code that follows a logical structure, proper use of white-space, well-name variables and methods, etc is far easier to read and debug than code that has a lot of comments. Comments are non-standard and difficult to search for when looking for a problem.

    Comments are best reserved for things which are non-trivial to figure out by reading and following the code.

  13. 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
    1. Re:Choice of Language by Nerdfest · · Score: 1

      Exactly. If you're coding in Assembly, you damn well better comment, but if you're coding in Java, I'd better not need much, if any. Generally, any high level language code in need of a lot of comments should never make it through code review.

    2. Re:Choice of Language by Gorobei · · Score: 1

      Yep. I've spent the last four years getting ex-Java programmers (retooled for Python,) to write less comments. Don't explain, just do. And do in a clear fashion without pointless abstraction, design pattern fluff, interfaces and other enterprisy stuff.

    3. Re:Choice of Language by ricotest · · Score: 1

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

      Perl has support for OO, ranging from the built-in stuff to a full-blown object system like Moose. Perl also has an inline documentation system called POD that bears some similarity to Javadoc. This leads me to conclude that you either don't know what you're talking about, or have been working with very bad Perl programmers.

      At my place of work, any code I write is likely going to be maintained for years, perhaps decades; even if it doesn't, someone else is going to end up having to fix something or add a feature, or perhaps it will be deprecated only to be pulled out of retirement later. I typically write a few paragraphs to describe the class (with example instantiation and usage) plus perhaps a sentence or two per method. None of that Javadoc-style documenting every argument and return value separately, though. But I make it decent, because even if the class is relatively simple, it might not be simple in a year's time - and if the documentation isn't there to begin with, future contributors might not bother to add their own.

    4. Re:Choice of Language by mandelbr0t · · Score: 1

      Heh. Check out the Chess module on CPAN. I most certainly do know what I'm talking about. And yes, the Perl programmers I've had the misfortune of working with have been bad to awful.

      --
      "Please describe the scientific nature of the 'whammy'" - Agent Scully
    5. Re:Choice of Language by mandelbr0t · · Score: 1

      Oh, and nearly forgot to mention a key point. Perl 5.8 has support for code that looks object-oriented, and supports namespaces to help with organization, but it is not truly OO. There's some syntactic sugar added to make things work generally like an OO language, but there's a lot of hacks that don't exist in a real OO environment. Manipulating the ISA array, for instance, makes non-OO things possible. Even with 'use strict', it leaves a lot to be desired. I can't speak to Perl 6, though. I've decided on Java as my language of choice, and I'll even work in C# if I don't have to work for Microsoft drones.

      --
      "Please describe the scientific nature of the 'whammy'" - Agent Scully
    6. Re:Choice of Language by Anonymous Coward · · Score: 0

      Sure I don't get hired to write code anymore, but I don't care.

      Nice job not documenting your work, hotshot. No, wait, the word I was looking for was primadonna, no actually smartarse, wait perhaps egotistical douchebag fits best. You're so great that you awesomed yourself right out of employability.

    7. Re:Choice of Language by Anonymous Coward · · Score: 0

      Are you high?

      Object oriented code can be so nasty to debug - generally it turns in to Java (massive disrespect!) even if it started as c++ - unreadable, comments say nothing useful, and no over all picture so I get it.

      I recall recently ripping through thousands upon thousands of lines of disjointed crap to identify that a character string was not properly null terminated. The problem showed so far from the origin that it wasn't even possible according to the author and the maintainer, but there it was, a nasty bug that only showed it the heap block happened to be the last one allocated.

      We'd all be better off if Java never happened. C++ gets OO right, Java fucked it, and now people try to program C++ as Java.

    8. Re:Choice of Language by Anonymous Coward · · Score: 0

      Ok hotshot,

      You don't need to assume the person following you is a moron, you just need to assume that it is not you, and that they have a different work history, and that they were born in 2012, and don't really have a lot of experience with ancient deprecated languages like Java.
      Take pity on the person who comes in 7 years time after you've retired with your millions and is asked to make your code do something you hadn't foreseen,
      or fix that bug you didn't notice. Oh sorry, I didn't mean to insinuate that you write bugs but, you know maybe someone else who came after you did it because
      they didn't quite understand the inner workings of your program correctly BECAUSE THERE WERE NO FREAKING COMMENTS!.

      Object oriented languages are in my opinion the easiest to get weird hidden bugs in and can be the hardest to understand sometimes. "multiple bug inheritance"
      comes to mind. Anyone who feels that they need to comment less because they write in this or that language needs to take a good look at themselves in the mirror and ask if they are really as smart as they think.

    9. Re:Choice of Language by doulos05 · · Score: 1

      That's as far as I'm willing to go to ensure that my code quality is good

      Really? That's a horrible attitude. I hope I never have to work on code you've written. "I did this and this, but if that's not good enough, sucks to be you. I refused to do anything else.

      Regardless of whether you think commenting is stupid from a technical perspective, if you're asked to, shouldn't you just do it? I mean, is it really that harmful?

  14. I am NOT a coder... but... by GuyFawkes · · Score: 1

    I suspect comments in code are like project notes.

    Even when I come back to my own projects a year or so later, it is obvious what I was doing with x widget attached just so the y widget.

    It is rarely obvious WHY I came around to that solution.

    Project notes, and I suspect good comments in code, address the though processes behind doing something this way, rather than explaining in detail WHAT the code does.

    10 REM FOR 16 BIT NMS MACHINES
    20 FOR X=1 TO 10
    30 PRINT "HELLO"
    40 NEXT X

    (told you I wasn't a coder)

    But line 10, the comment may be very useful, aha, that's why this works on X machine but not X machine, etc.

    --
    http://slashdot.org/~GuyFawkes/journal
    1. Re:I am NOT a coder... but... by fishexe · · Score: 1

      10 REM FOR 16 BIT NMS MACHINES
      20 FOR X=1 TO 10
      30 PRINT "HELLO"
      40 NEXT X

      (told you I wasn't a coder)

      But line 10, the comment may be very useful, aha, that's why this works on X machine but not X machine, etc.

      If you have a machine which both supports a BASIC interpreter and doesn't support your lines 20-40, I think you have bigger problems than whether or not somebody commented this block of code.

      --
      "I don't care about the Constitution!" --Bill O'Reilly, November 17, 2009
  15. 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?
    2. Re:Does he think comments are pseudocode? by Arimus · · Score: 1

      Depends, if you are using doxygen style comments and change the function header then the comment changes...

      --
      --- Users are like bacteria -> Each one causing a thousand tiny crises until the host finally gives up and dies.
    3. Re:Does he think comments are pseudocode? by noidentity · · Score: 1

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

      No problem, just add some comments to explain the details.

    4. Re:Does he think comments are pseudocode? by Anonymous Coward · · Score: 0

      If your comments don't need to change when you change the way you do something then YOU are doing it wrong. You should be saying why you chose to do it that way and of you choose to change the way you do something then you should probably be saying:

      1/ Why the obvious way you chose before doesn't work.

      2/ Why you are doing it the new way.

      Comments are to help someone else (or you in 2 years) understand the WHYs of the code. Especially the hidden ones, such as dependencies on other code.

    5. Re:Does he think comments are pseudocode? by Dom2 · · Score: 1

      Exactly the point of the article...

  16. 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 Anonymous Coward · · Score: 0

      slow news day. new here?

    2. Re:So who is this guy? by Anonymous Coward · · Score: 0

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

      IT'S BOOKS 2.0

    3. Re:So who is this guy? by oogoliegoogolie · · Score: 1

      I have no idea who this guy is either. Can someone fill us in?

    4. 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.
    5. Re:So who is this guy? by anti-NAT · · Score: 1

      Here's his bio - still nothing that shows that his insights are exceptional, or supported by years and years of experience or practice.

      http://jasonmbaker.wordpress.com/about-me/

      --
      The Internet's nature is peer to peer - 20050301_cs_profs.pdf
    6. Re:So who is this guy? by anti-NAT · · Score: 1

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

      That'd have been more original :-)

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

      I think we can answer the question pretty easily: Some guy who wanted to increase the Google rank of his blog and somehow made it through the firehose.

      --
      I am officially gone from /. Long live http://www.soylentnews.com/
    8. Re:So who is this guy? by obarel · · Score: 1

      What always amazes me is that such things get a huge reaction. How many "news" articles are we going to read about comments in code? How many people are going to change the way they write code after reading through these threads?

      Here's a summary:
      1. Code should be self-documenting
      2. But then it doesn't explain WHY
      3. But comments are just lies after 10 years
      4. If it was hard to write, it should be hard to read (actually I haven't heard that one in a while ;-)
      5. I hate comments like /* increment i */
      6. Yeah, try reading the code to the nuclear reactor that I'm working on without the comments that refer to the design
      7. Why is this news?

      I hope this concludes any future articles about commenting code. While we're at it, please don't write 1500-line functions, not every word has a readable abbreviation and there are better ways than nesting 11 if statements.

    9. Re:So who is this guy? by Anonymous Coward · · Score: 0

      But the Y2K+10 bug is here. If your mail is sorted by SpamAssassin, there's a good chance you have some false positives in the spam folder: SpamAssassin assigns spam points to mails where the year matches /20[1-9][0-9]/ because the year is "too far in the future". Oops.

  17. Compare / contrast. by fahrbot-bot · · Score: 1

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

    Depends on the efficiency and maintainability. A one-liner that's "perfect" is probably worth the extra comments. Ten lines of self-evident code may not be better. Personally, I can't stand code that starts "boolean done = false; while (!done) {...}" when the condition can be determined inline using an operational variable.

    --
    It must have been something you assimilated. . . .
  18. "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?)

    1. Re:"would you rather use a one-liner" by Xugumad · · Score: 1

      Exactly. A code-monkey can talk about just writing raw lines of code, but any serious software developer will spend far more time designing the architecture of the code, than actually typing it in...

    2. Re:"would you rather use a one-liner" by careysub · · Score: 1

      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.

      Amen to that brother!

      I am also much aggrieved by the corollary: junior developers coming up to me to complain about my "bad coding" - i.e. writing visibly nested loops with clear indentation of each level, and separating different logic tests into different statements, instead of mashing everything together into a few unindented lines.

      --
      Starships were meant to fly, Hands up and touch the sky - Nicky Minaj
    3. Re:"would you rather use a one-liner" by Anonymous Coward · · Score: 0

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

      Yesterday.

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

    1. Re:every line of code should be commented by mandelbr0t · · Score: 1

      Parent marked troll? I think it's very funny.

      --
      "Please describe the scientific nature of the 'whammy'" - Agent Scully
    2. Re:every line of code should be commented by Anonymous Coward · · Score: 0

      Sadly, this is actually how some places teach commenting, apparently. On a C forum I contribute to, posters will occasionally post code that is wildly overcommented. There are literally comments along the lines of "these are the declarations".

    3. Re:every line of code should be commented by owlstead · · Score: 1

      In Java CheckStyle I've disallowed any statements that have been placed behind the code instead of on the line right in front of it. There are a few reasons for doing so: 1) they can be easily overlooked 2) they tend to explain the how instead of the why (which is a mistake most of the time) 3) people tend to use spaces to format them and 4) they tend to go over the 120 column mark we've set during refactoring.

      So none of the lines except maybe the line containing just else would have been marked with a warning :) (yes, I know, I am responding to a jest).

    4. Re:every line of code should be commented by careysub · · Score: 1

      I'd rate if funny too... if I hadn't actually worked in environments where commenting of this sort was actually required...

      --
      Starships were meant to fly, Hands up and touch the sky - Nicky Minaj
    5. Re:every line of code should be commented by JoeMerchant · · Score: 1

      You know, I do those close brace comments, but usually with a copy of whatever opened them:

      } // if ( dome )

      Yes, the smart editor will highlight the block for me, but many times (especially in code I didn't write) the block is bigger than the page....

    6. Re:every line of code should be commented by Anonymous Coward · · Score: 0

      I'm honestly suprised nobody has taken this seriously and tried to admonish you for it.

      This is Slashdot, after all.

    7. Re:every line of code should be commented by Imagix · · Score: 1

      Sorry, you've failed code review. I don't see a comments on the "else" line.

    8. Re:every line of code should be commented by Anonymous Coward · · Score: 0

      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.

      I would give you a b- for this, comments should be on their own line as it makes it easier to read

    9. Re:every line of code should be commented by Anonymous Coward · · Score: 0

      cool! what does that "else" line do ?

    10. Re:every line of code should be commented by Anonymous Coward · · Score: 0

      /* You don't use // in C. */

    11. Re:every line of code should be commented by Anonymous Coward · · Score: 0

      What does "else" do? It's not commented...

    12. Re:every line of code should be commented by Anonymous Coward · · Score: 0

      FAIL

      You forgot to comment "else"

    13. Re:every line of code should be commented by ByteSlicer · · Score: 1

      Line comments (//) are part of the 'new' C syntax (C99). Most modern compilers support it.

    14. Re:every line of code should be commented by Anonymous Coward · · Score: 0

      That looks far too close to what I was taught at University to be a joke. We were seriously taught to end if statements and functions with "// End of blah" type comments.

    15. Re:every line of code should be commented by baileydau · · Score: 1

      You know, I do those close brace comments, but usually with a copy of whatever opened them:

              } // if ( dome )

      Yes, the smart editor will highlight the block for me, but many times (especially in code I didn't write) the block is bigger than the page....

      I agree totally. I routinely do this.

      As well as not having the entire block on the same page, sometimes the editor looses the plot with brace matching, especially if there is some commented out code in the middle somewhere.

      There is also the issue of accidentally deleting a brace (typically closing). This obviously results in a syntax error, but it is much quicker to find if they are appropriately marked.

      I also tend to flesh out my coding. In the UML editor, I tend to add a comment as to what the method, class, whatever is to achieve (not for trivial stuff though). I find this helps when there is a period of time between original design and building it.

      When I'm writing a method, I quite often start with a series of comments stating what should happen at a high level, then I start filling in the details. I find marking the end of each block helps that process.

      --
      Ever stop to think ... and forget to start again?
    16. Re:every line of code should be commented by mehrotra.akash · · Score: 1

      somehow all my C/C++ books are written like this

    17. Re:every line of code should be commented by Anonymous Coward · · Score: 0

      You forgot to comment the line that says "else"; in addition, it's not an "if" block, but an "else" block.

      You just pointed out (intentionally?) what I dislike the most about comments. First I read the code, *then* the comments, *then* whether *both* are consistent and make sense with each other. In case they don't (they often don't) which one should prevail?

    18. Re:every line of code should be commented by Anonymous Coward · · Score: 0

      //previous version did not work for negative i

      unsigned int doit(unsigned int i) {
        if(i!=0) i+=doit(i-1);
        return i;
      }

    19. Re:every line of code should be commented by Tanuki64 · · Score: 1

      I do it sometimes too, when I have to understand bad code with many nested loops. However, if I am allowed to do it, and the the code and project situations allows it, I tend to refactor the code. The necessity to mark the end of a loop is definitely a code smell. Usually it is not too difficult to convert several nested loops in a group of easily readable functions. If it is, it is even a worse sign regarding code quality. Yes, exceptions exist.

    20. Re:every line of code should be commented by JoeMerchant · · Score: 1

      Yes, it (far reaching brace pairs) is code smell, unfortunately if the smelly code works, there are usually more important things to fix. Now, if the smelly code needs to be changed significantly for some reason, that's when refactoring is in order.

    21. Re:every line of code should be commented by Anonymous Coward · · Score: 0

      You forgot to document the 'else'.

  20. 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.
    3. Re:You made his argument for him by Anonymous Coward · · Score: 0

      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

      When I was working on my very first job, I wrote a demo program for a CAD system for utility networks (in LISP, no less). When we gave the demo, and got the contract, the head of the tiny company asked to review my code. I printed it out, and we sat down for about 10 minutes, while he paged through it, not saying a word. He closed the listing, looked at me, and said:

      "When you don't comment your code, you're saying this". and gave me the finger.

      I've been pretty religious about it since then. strcmp doesn't get 3 lines, but the code to generate the line-of-sight coverage from a cell-tower in ultra-hand-optimized code sure did.

      There's a very common reason to put in kludgy non-intuitive code: to work around other non-intuitive kludgy code. In many organizations, it takes an act of God in triplicate with Torquemada in the code review to change existing code, no matter how bad.

      1) "This code is already tested"
      2) "Customers are already using it and we can't risk a regression" ... blah blah blah...

      and when you're forced to write something awful, the least you can do it write something about why.

      In general, I find the worst programmers don't document their work. At. All.

    4. Re:You made his argument for him by SharpFang · · Score: 1

      I have a simple rule. If some code deserves 15 lines, it should get 15 lines, be that code or comment. If I can squeeze the code into 3 lines, I ought to sacrifice the remaining 12 lines to comment. If I write 15 lines of self-explainatory code, it requires no further comments.

      Reverse hashes are a special case where comment is very desired.

      index[ reverse_hash[ value ] ] when you use exotic multiply inherited variables is one point that well deserves good 10 lines of comment the code would require was it a reverse search written as a straightforward loop.

      --
      45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
    5. Re:You made his argument for him by Anonymous Coward · · Score: 0

      Actually you could just play the code and hear the chords come out right.

    6. Re:You made his argument for him by Anonymous Coward · · Score: 0

      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.

      I don't see why assigning 42 to a constant requires 3 paragraphs of comment...

  21. 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?
  22. Should be... by Restil · · Score: 1

    myths about excessive code comments. Provide comments in places where the comment might be useful. If you have some obscure function, the purpose of which might be confusing if you or someone else looks at it a year later, then you need a comment. The more obscure or terse, the more detailed the comment should be. On the other hand, if the function's purpose is obvious just by glancing at it, or the function name is sufficient to describe the entire purpose of the function, there's probably not a need for any comments at all.

    Within a function, if you only have nested loops one deep, there's probably no need to comment each closing bracket. But if you have some horrendous 12 dimensional loop with lots of if statements, it might save a few headaches to know exactly which bracket lines up with which routine.
    It's just a matter of commenting what is necessary, and avoiding it when it's not.

    -Restil

    --
    Play with my webcams and lights here
  23. Thank you.. by Anonymous Coward · · Score: 0

    ..very much for mentioning this. Screenshots so far look very promising.

    ---> Fresh installation of devel/geany started at: Sat, 02 Jan 2010 00:07:31 +0100
    ---> Installing 'geany-0.18' from a port (devel/geany)

  24. Employment prospects by paylett · · Score: 1

    This, in an age when prospective employers are known to check out candidates blogs. Entertaining.

    --

    Believing something doesn't make it true. Not believing something doesn't make it false.

    1. Re:Employment prospects by russotto · · Score: 1

      This, in an age when prospective employers are known to check out candidates blogs. Entertaining.

      Proof by darkly suggesting serious real-world consequences to advocating an opposing position. Amusing, but not rhetorically valid.

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

    1. Re:Strongly RESTRICT Code Commenting by Xugumad · · Score: 1

      Okay, so lets talk some of the code I have to deal with on a day to day basis...

      int getGradeSourceHumanPosition(int sourceID)

      What does that do? What's a source ID? What does human position mean? That's a method in an API, as listed. We argue over this a lot, but I maintain that it's essentially impossible for the initial developer to understand what someone coming to the API later on will find confusing, and at the very least exposed methods need to be documented...

    2. Re:Strongly RESTRICT Code Commenting by Anonymous Coward · · Score: 0

      Reminds me of a chunk of PHP code that I was asked to "refactor" ... Every single file (about 70 of them) came with a 30-line copyright notice, followed by intermixed fragments of PHP and HTML. There were no comments in any of the files and each usually came with braces on either side of HTML blocks. Needless to say it ended up rm -rf 'ed ... Sometimes it is just faster to start over.

    3. Re:Strongly RESTRICT Code Commenting by JoeMerchant · · Score: 1

      One routine I have written a couple of times that NEEDS comments is a cubic spline interpolation, the algebra is thick, and if you do it well, your code skips about 80% of the steps due to zero values in the variables. Even with the zeroing, there are about a half dozen intermediate variables computed and it is all too easy to make a mistake along the way.

    4. Re:Strongly RESTRICT Code Commenting by jhp64 · · Score: 1

      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.

      A fourth reason: if you use something like Sphinx to autogenerate documentation from your code, then you should probably include at least a one-liner saying what each function or method does, and maybe you want to describe the parameters and the return values. (If you're using a language like Python, then of course you don't have the types of the parameters or the return values in the function definition, so you should document them.)

      --
      This is the way Bi-Coloured Python-Rock-Snakes always talk.
    5. Re:Strongly RESTRICT Code Commenting by omb · · Score: 1

      Your example makes the shit-api and how not to write code points perfectly, and BTW this CRAP is 99.9% caused by OO mumbo-jumbo. The advice given by a well known British politician id perfect here "If you find yourself at the bottom of a hole, stop digging!"

      If this is part of a library where is the API documentation, and why wasnt the code written sensibly in the first place:

      vide:

      int getUSassimilatedGrade(int employeeSystemUID_Id)

      or somesuch, when I am faced with this sort of crap, which is often, I find out who, in purchasing, bought the nonsense, and get them to give me the name of their sales contact and through him get to the guy who wrote the rubbish and get some useful documentation not written by doc-writers and add that to my copy of the product data.

      We are having problems unifying some aspects of (personal) reference data (stamdaten) in Europe, Names, addresses ... which vary by state, and have lots of hidden semantics, often special and very local eg CH-8054 Zurich is in kreis 4, and the only way of finding about that stuff is asking questions, and having done that write it down, in the code, that is case (b) above.

    6. Re:Strongly RESTRICT Code Commenting by omb · · Score: 1

      Yes, but I wrote on code commenting, and project documentation is an other thing; personally I dont like doc-generators much more complex than the perldoc level, and can not figure out what most of them especially Doxygen are really trying to do, I find them useful as Xref and visualization tools, and I suppose, with great discipline you could get Javadoc ... to work but at that point you are back in what, not why. I like Wikis better, and they are searchable. I use SourceNavigator as a code visualiser, and then "Read the Code, Luke [Tovolds]".

  26. 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 complete+loony · · Score: 1

      I dunno, I was going to say something similar to the OP. Code spread over too many lines takes longer to understand as you have to trace through everything before you can piece it all together in your head. And before you can refactor it you have to understand all the different logic branches.

      --
      09F91102 no, 455FE104 nope, F190A1E8 uh-uh, 7A5F8A09 that's not it, C87294CE no. Ah! 452F6E403CDF10714E41DFAA257D313F.
    3. 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?!
    4. Re:Less verbose is more writeable by swillden · · Score: 1

      Your example misses the point precisely because it's just as clear in one line than in eight.

      Except it's not "just as clear" in one line, it's clearer.

      More lines, less lines, more comments, less comments -- the goal is clarity. More precisely, the goal is to minimize the level of effort required to understand and modify the code, and part of the effort required to understand is the effort required to read, and part of the effort required to modify is the effort required to update any comments.

      All of the costs have to be considered, an an appropriate tradeoff chosen.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
  27. 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.

  28. I can answer that one! by Zero__Kelvin · · Score: 1

    "This is about as close to being a canonical "bad comment ", and yet people who should know better still do it. Why? Because they feel that they should document every function or class. The reality is that documenting something that needs no documentation is universally a bad idea."

    The reality is people might know more than you, and you are assuming that you are an uber-programmer when you are not! Maybe the programmer is more qualified than you to write Python (the language the example is in in TFA) and uses pylint. Maybe he doesn't want to sift through 272 warning messages to see which are important and which are superfluous, so he is consistent. Maybe consistency is a good thing in the software domain. Maybe he also wants every member method to be consistintly documented since docstrings are tied in memory to the object and available via help(object).

    I am encouraged by most of the comments about comments here on Slashdot thus far. Most people seem to get why comments are a good thing. The author doesn't write them off completely of course, but he is not qualified to write this article either. There is just too much he doesn't yet understand, and he would do well to ask these questions of a qualified software engineer rather than posing them as rhetorical, since in a lot of cases he doesn't know the answers but mistakenly thinks he does, as I have shown.

    There is a reason why language designers pretty much universally include a comment mechanism, and why that mechanism has been trending toward the docstring / formal approach away from the "willy nilly" techniques of old rather than removing the ability to comment completely.

    --
    Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
  29. Useful comment: by Albert+Sandberg · · Score: 1

    // Message below is written by an idiot, jsyk

  30. This guy is WRONG. by sootman · · Score: 1

    "documenting something that needs no documentation is universally a bad idea"

    -- yeah, because everyone in the world has the exact same experience and knowledge, so something that's obvious to one person is obvious to the rest of the world and vice-versa. And nobody ever changes, learns new things, or uses things that are obvious now but will be completely forgotten after five years of not using that particular construct.

    This guy's opinions are worth less than the comments he eschews.

    --
    Dear Slashdot: next time you want to mess with the site, add a rich-text editor for comments.
  31. 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.

  32. Re:Shorter sentences by paylett · · Score: 1

    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.

    Complexity of that last sentence:
    * 52 words,
    * 17 punctuation characters,
    * 5 parentheses blocks,
    * at least half a dozen ideas.

    But I'm just having fun. I agree with you 100%.

    --

    Believing something doesn't make it true. Not believing something doesn't make it false.

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

    1. Re:compares to all professions by dodobh · · Score: 1

      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

      The magic word here is competent. If all programmers were equally competent, then things would be easy. They aren't.

      Some people find one-liners easy to read. Others find that the one-liner is too complex.
      Some find it easy to work with immutable data structures and message passing. Others cannot live with complex, heavy objects, mutable data structures and method calling.

      Given the level of variation in programmers (and the quality output), it is hard to follow a specific policy on comment quality.

      --
      I can throw myself at the ground, and miss.
  34. Code format by omb · · Score: 1

    Is very important, and it be consistent is more so; a good editor Vim or Emacs and code beautifier is your friend. Often you will need to temporarily re-format code, as you work on it, but in a big code base root-nd-branch reformats must be very rare, it screws up the SCM history, so I often re-format, fix get patch, revert, apply patch. Git etc makes this very easy.

    Personally I hate the KR if (foo) {

    } style. I like

    {
    }

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

    drop, but I cant always get what I like.

    1. 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.
    2. Re:Code format by Anonymous Coward · · Score: 0

      And then there's tabs vs. spaces, and tabs at 4 or 8 characters (or even 2?)

    3. Re:Code format by TheRaven64 · · Score: 1

      The 80-column limit is based on the human visual system's ability to track lines of text, not the width of the terminal. A better constraint would be that a line can't contain more than 66 non-space characters, but 80 columns is a good rough approximation of this that also ties in prevention of excessive scope nesting.

      --
      I am TheRaven on Soylent News
    4. Re:Code format by digitig · · Score: 1

      Oh, that one's easy. Write it the way you like, and write scripts that convert it to and from the corporate standard when you check it in/out.

      --
      Quidnam Latine loqui modo coepi?
    5. Re:Code format by brausch · · Score: 1

      I call BS.

      80 columns is how many characters fit on a punch card. Period. They made terminals to be that width because of the punch cards, not the other way around. I programmed for a quite a few years before the glass terminal was even invented.

      --
      "Almost every wise saying has an opposite one, no less wise, to balance it." - George Santayana
    6. Re:Code format by daVinci1980 · · Score: 1

      Citation needed.

      The reason it's the number 80 was rather arbitrary, but a throwback to old punch-card systems.

      --
      I currently have no clever signature witicism to add here.
    7. Re:Code format by Logic+and+Reason · · Score: 1

      By making lines 160 characters long you force everyone to have to code the same way you do.

      Did you know that there are editors that can wrap text for you? Truly, we are living in the future!

      What is lost to you by breaking a line at 80 characters...

      I don't know, how about the ability to use lines longer than 80 characters? There's also the manual reformatting you have to do when you edit a line of text, which is a complete waste of time.

      Now, I'm not saying you should never break up statements into multiple lines. But do so only to elucidate the structure of the statement, not to conform to some arbitrary column width to accommodate back-asswards coders who can't be arsed to use a modern editor.

    8. Re:Code format by shutdown+-p+now · · Score: 1

      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.

      Well, no developers on my team have windows that narrow that they require 80 chars per line to fit. In fact, all of them have a 24" monitor, and normally code full screen. Now what?

    9. Re:Code format by TheLink · · Score: 1

      Decent editors can wrap lines (and let you know they are wrapped). So they're not forcing you to scroll left and right, unless you're using a really crap editor. Most text editors can wrap. Even Windows Notepad can.

      By forcing everyone to 80 characters, you're forcing everyone to code the same way you do. By breaking lines at 80 characters, you're forcing some of them to scroll up and down when they wouldn't have to. Not so many editors can unwrap forcibly broken lines.

      So forcing 80 character lines is very inconsiderate to the rest of the team.

      It's easier to read code when you don't have to keep scrolling up and down. You can just stare and concentrate at stuff on the screen till it makes sense.

      As for the convention of:
      {

      }

      That wastes a line and increases the amount of scrolling you have to do, for very little gain in code clarity.

      I prefer to use tabs and leave tabs as tabs. Then everyone can have the indentation to be has much or as little as they want (so that it can fit on their narrow or wide screens).

      Then put a comment at the top saying how many "spaces" your tab is (or where your tab stops are), then others can read stuff the way you wrote it and still be able to switch to whatever they like.

      --
    10. Re:Code format by dkf · · Score: 1

      As for the convention of:
      {

      }

      That wastes a line and increases the amount of scrolling you have to do, for very little gain in code clarity.

      Lines are cheap. If it's causing you to have blocks of code that are too long, those blocks of code are too long anyway. (Sometimes you're stuck with long code blocks, but usually not.)

      I prefer to use tabs and leave tabs as tabs. Then everyone can have the indentation to be has much or as little as they want (so that it can fit on their narrow or wide screens).

      Then put a comment at the top saying how many "spaces" your tab is (or where your tab stops are), then others can read stuff the way you wrote it and still be able to switch to whatever they like.

      I prefer to force tabs to be 8, and leave it optional whether or not to use them. That works better with the defaults across lots of software (e.g., web browsers for viewing patches online).

      For indentation levels, 3 or 4 spaces seem to work well. Less and it's not distinctive enough (to my eyes), more and it's just wasteful.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    11. 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.
    12. Re:Code format by Logic+and+Reason · · Score: 1

      Then put a comment at the top saying how many "spaces" your tab is (or where your tab stops are)...

      There's no reason to even do this unless you're aligning tabs with other characters, which you should never do precisely because tabs widths vary. Use tabs only at the beginning of a line for indentation, and not to create "columns" in variable declarations, hash maps, etc. (Personally, I can't stand that layout style anyway.)

    13. Re:Code format by petermgreen · · Score: 1

      IMO the real question is does breaking longer statements accross lines and hence breaking the structure really leave code more readable than simply having long lines for such statements? IMO it doesn't.

      This is especially bad in modern languages and coding styles where names tend to be longer and often have an asccociated object (java's lack of support for properties* and the consequent requirement for typing get and an empty pairs of brackets for many of the parameters makes things even worse)

      * Properties in this context are items that look to the user of the object like fields but can have code behind them to take actions on a get or set. Delphi's implementation is particularlly nice because if you wish you can map a property directly to a field for read while having it call code for write (you can also have it call code for both read and write).

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
    14. Re:Code format by bingoUV · · Score: 1

      Right. 80 is not such a hard requirement. It must be subjectively defined as per circumstances. Where I work, upto about 120 characters for java code is considered all right. But we discourage more than 80 characters for perl.

      This doesn't take away from the fact that such limits/best practices/guidelines should be defined on a project wide basis rather than left to each individual developer.

      --
      Bingo Dictionary - Pragmatist, n. A myopic idealist.
    15. Re:Code format by http · · Score: 1

      The default $COLUMNS in VGA mode on a PC is 80.

      --
      If opportunity came disguised as temptation, one knock would be enough.
      3^2 * 67^1 * 977^1
    16. Re:Code format by shutdown+-p+now · · Score: 1

      Do you code in VGA text mode? Do you know anyone who does so today?

    17. Re:Code format by jgrahn · · Score: 1

      There's no reason to even do this unless you're aligning tabs with other characters, which you should never do precisely because tabs widths vary.

      No they don't. The standard TAB width is 8. If the team doesn't agree on that, the only sane choice is to ban TABs (which many do). I have seen some people argue (like you) that sticking exclusively to TABs for indentation and using them for nothing else means a guy with 8-TABs can cooperate with 3, 4 and 5-TAB people, but I suspect that it would break down in practice. It would also be hell for anyone who uses standard 8-TABs but finds an 8-space indentation intolerably deep -- i.e. for most people.

      Use tabs only at the beginning of a line for indentation, and not to create "columns" in variable declarations, hash maps, etc. (Personally, I can't stand that layout style anyway.)

      Agreed, at least for variable declarations. That this style sucks gets very obvious when you have to change/add a type or a variable name, and are forced to realign a whole list of unrelated things around it. (Yes, you have to reindent when you add a nesting level too, but that's much more rare and there's usually no way around it.)

    18. Re:Code format by Logic+and+Reason · · Score: 1

      No they don't. The standard TAB width is 8.

      The fact that you had to qualify your statement with the word "standard" supports my point. And what "standard" are you referring to, anyway?

      I have seen some people argue (like you) that sticking exclusively to TABs for indentation and using them for nothing else means a guy with 8-TABs can cooperate with 3, 4 and 5-TAB people, but I suspect that it would break down in practice.

      Why do you suspect this? It sounds like you haven't actually tried it. I can and do sometimes view the same file with different tab widths, depending on which section I'm working with. There are no problems as long as you use only tabs for indentation, and spaces for all other formatting. And it's easy to fix when someone does the wrong thing.

      It would also be hell for anyone who uses standard 8-TABs but finds an 8-space indentation intolerably deep -- i.e. for most people.

      But if tabs are used only for indentation as I suggested, then these people can set the tab width to whatever they want without impacting anything besides indentation.

    19. Re:Code format by wzzzzrd · · Score: 1

      Amen brother. Unless you are doing something like linux kernel development which may force you to use a terminal editor at 80x25, the 80 characters rule is stupid (and even then you can just reformat the text). I HATE it when the 80c rules breaks up statements and makes them unreadable.

      --
      On second thought, let's not go to Camelot. It is a silly place.
  35. 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...

    1. Re:The flipside by Anonymous Coward · · Score: 0

      Reverse engineering code is as hard as the code. The comments make no difference. The real place for documentation to be is on documentation.
      Comments should be left for things such: /* This might seem to be a race condition but it isn't because ... */
      Where review might introduce bugs.

    2. Re:The flipside by merreborn · · Score: 1

      For what it's worth, your diatribe comes off as fairly melodramatic. You'd do well with a rewrite that puts more emphasis on the largest issues (management having no idea how long projects should take, lack of air conditioning, coworkers incapable of basic communication), de-emphasizing the most trivial complaints (manager that checks in "up to 3 times a day"? A company focused on profit? These seem par for the course), and omitting the dramatic hyperbole entirely -- especially the repeated mentions of being "almost in tears", and the paragraph of suicidal ideations.

      It was clearly a lousy job, and you were right to leave, but the way you've written your account doesn't put you in a terribly positive light either.

  36. Knuth by SEWilco · · Score: 1

    I believe that Knuth had volumes to say about code and documentation.

  37. Don't listen to this crap by MacGyver2210 · · Score: 1
    FTA: "If anything, comments make code less readable. Nine times out of ten, I ignore comments unless I'm stumped. In fact, I'm tempted to make emacs hide all comments unless I explicitly expand them."

    I stopped reading at this point, because the author is clearly a terrible programmer and not someone I want to take coding/commenting advice from. If you do comments right, which this guy clearly doesn't, they can save your ass repeatedly and avoid having to go to deeper, harder-to-reach documentation to make it work. Clearly not someone with any real programming experience behind this 'article' (although it looks more like a twitter feed).

    --
    If the only way you can accept an assertion is by faith, then you are conceding that it can't be taken on its own merits
    1. Re:Don't listen to this crap by owlstead · · Score: 1

      I do believe he was commenting on other peoples comments not his own.

      (In other words, just like this is a comment on your comment and not on my own comment and your comment was a comment on the author who made a comment on other peoples comments. Since this comment was on the comment about your comments all this should probably be considered reflective meta comments and non-reflective meta-meta comments.)

  38. some comments good.. by itzdandy · · Score: 1

    I believe that some comments are good but overcommenting is messy. I prefer to do my commenting in blocks as small descriptions of what the code is indended to do.

    I like to organize my subroutines and objects etc by their type. This way I can search my code for 'OBJECTS' and fine the section that describes objects or 'SUBROUTINES' and I will have made sub sections via comments 'SUBROUTINES_SEARCH' etc etc. I like few, simple, concise comments. I do a lot of work in bash for administering servers but bash scripts should be clean and properly commented just like C or PHP etc.

    #!/bin/BASH
    #Code specific to bash or bash compatible shells. author *ME*

    # INCLUDES
    include /etc/script.conf
    include /usr/share/script/functions/*

    # SUBROUTINES
    [item1]
      #workorder5678 custom;
      function1;function2;#end wo5678 1/1/2007, edit 3/18/2007;
      function3;end;

    [item2]
      function1;function2;function3;end;

    #end

    NOT

    #this is item1. i like to put long comments that are as big as the code.
    #i dont consider the fact that anyone reading these scripts in the future only
    #needs to know why I did this and what it is supposed to do, not how it does it. if you dont know how it does it then you are in the wrong job
    [item1]
    function1;function2;function3;end;

    #this is item2. it is almost like item1 above.
    #I know I shouldn't reference physical locations in a file because they might move for organization but
    #I thought id put a note in here that item2 references item3 with is at line 652 and item3 references item1 which is right above this on line 601.
    [item2]
    function1;function2;function3;end;

    I think an important definition to point out is that 'comment' is not the same as 'document'. Put comments in to assist you in the future, to find code, to give a quick hint at the functions intended use so you can use that code better. Dont describe how to do a if/fi statement or how to use a function.

    1. Re:some comments good.. by Tanuki64 · · Score: 1

      Wow, great. Without "#Code specific to bash or bash compatible shells. author *ME*" I would have to try dozens of script languages before I'd find out that '#!/bin/BASH' means a bash script. And of course, without '# INCLUDES' I surely would have confused the folloing lines with macro definitions.

  39. Did anyone read the article? by garg0yle · · Score: 1

    The author's point (near as I can tell) isn't so much "comments are bad" as "most people comment incorrectly", which I would not argue with.

    Nobody who's actually worked on other people's code in the wild will argue that comments are bad (at least, nobody sane), but there IS a right and wrong way to comment. Unfortunately, while you can explain to newbies about commenting until you're blue in the face, they really won't "get it" until they've been there themselves.

    --
    Modding "-1, Troll" is not a proper response if you disagree with me. Try reason.
  40. 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
    1. Re:Where is your proof? by Anonymous Coward · · Score: 0

      "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 think he meant if you use absolutely no comments...

    2. Re:Where is your proof? by hughperkins · · Score: 1

      > Well that's not in the least psychotic.

      True, but no-one (few people?) enjoys debugging other people's work. They'd rather be writing their own green-field implementation using the latest cool technologies, .Net 3 or .Net 4, or Ruby, or Python 2.6 or whatever. Who wants to be debugging some COBOL stuff, or something written in C? Answer: very few people.

      So, when people are debugging other people's code, they (we) often would rather choose to dis' the other person's code, write it off as unmaintainable crap, so that we can justify it being replaced by something 'beautiful', using modern technos.

      But we can't ethically justify that, since, well, it's more expensive, and time-consuming to write it from fresh than just to maintain the old stuff for another few years.

      But we'll look for any excuse we can to make it more 'ethical' to justify that, and someone's comments, or lack of comments, are fertile ground for such 'justification'.

      So, when it's our own code that is being ripped apart by some intern who'd rather write their own code, the easier it is for the intern to understand the code, and understand our comments, the fewer excuses for said intern to bash our code, and the easier it is to fix the issue, and move onto something more interesting for them. It's win, win: they fix the problem quicker, and our code doesn't get dissed. Hopefully. Not so much anyway...

    3. Re:Where is your proof? by SuperKendall · · Score: 1

      I think he meant if you use absolutely no comments...

      Honestly that is preferable to code that has half (or more) of the comments out of date. Then at least there is nothing to mislead you.

      Or preferable to people that comment Every. Single. Line. Noise is noise, regardless the form.

      --
      "There is more worth loving than we have strength to love." - Brian Jay Stanley
  41. its the What was i drinking problem by RobertLTux · · Score: 1

    put comments in places where you may later need to remind yourself what you were thinking/drinking later (or if you get run over by a bus the next guy). Also in any places where you have to code around a bug in hardware or some other chunk of software make detailed comments.

    a request to programmers please have a function to dump a settings file with all the settings set to defaults
    (even those that would normally not be in the settings file)

    --
    Any person using FTFY or editing my postings agrees to a US$50.00 charge
  42. 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.

  43. Job Security by jamesh · · Score: 1

    Wasn't one of the mantra's of the humorous Job Security paper that someone published a while back that you should comment only the obvious stuff, eg:

    while (i epsilon(n))
    {
        i += (j + 47) * 55 - sqrt(r) + j * j - r * r - pom();
    }
    i++; // increment i by 1

    Myself, I comment next to nothing unless I suspect that I won't know what I was thinking if I come back to the code in 6 months. If I come back to code in 6 months and can't remember what it does or why it does it that way, I'll put comments in for next time.

  44. 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 swilver · · Score: 1

      It's a quote, not a fact.

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

      --
    6. Re:Kernighan by Anonymous Coward · · Score: 1, Funny

      yeah what the fuck did this Brian Kernighan fellow ever do that I should listen to what he has to say about coding ;)

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

    8. Re:Kernighan by Gavagai80 · · Score: 1

      Code drunk, debug sober.

      --
      This space intentionally left blank
    9. Re:Kernighan by Dahamma · · Score: 1

      Yeah, a quote from one of the more experienced, successful programmers in history. I'd trust his opinions more than those of the random blogger the article references.

  45. 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
    1. Re:Most of what you say is wrong by Twanfox · · Score: 1

      While I would tend to agree with you on URL references being invalid in 3 months or the life of a software product, whichever is sooner, literary references are often useful for archived references. Book references (including those used in writing papers or when used in citations) often require that you indicate the year of copyright. Subsequent editions (second, third editions, etc) will bear different copyright dates and should be obvious when locating a later version of a book. Whether or not the original is obtainable may be in question, but the reference and structure of identification of publications tends to be fairly standard and work over time.

    2. Re:Most of what you say is wrong by dcollins · · Score: 1

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

      That's flat-out crazy. By your argument the whole idea of footnotes and book references is nonfunctional. You may as well argue against the technology of writing and shared knowledge in general.

      --
      We know where leadership by an anti-intellectual "strongman" who scapegoats minorities and likes boisterous rallies goes
    3. Re:Most of what you say is wrong by jasampler · · Score: 0

      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.

      Imagine that you change a code many times for different reasons. Would you explain every possible change you did? For frequently modified code, nowadays you have an alternative for this kind of comments (and others): Putting them in the Versioning Control System. It will store not only the comment, but who changed the code and why, what other changes were made at the same time, when it was done and even all the rest of the program at that point. And code will remain clean and coming with only general explanations about it.

      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.

      After including one of them, you should always include a copy of the book or the webpage along with your code, and everything will be OK. Space is cheap, isn't it?

    4. Re:Most of what you say is wrong by Anonymous Coward · · Score: 0

      > comments are pointless (but harmless)

      No they are not harmless, they are detrimental to readability and cost the reader time (to read them)

  46. self-documenting by onefriedrice · · Score: 1

    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?')

    Not sure if that example supports his claim very well... After all, four lines is less than ten, and if you can adequately describe what the function should do in three lines, somebody should easily be able to flesh it out themselves if ever a need arises. I'm all for self-documenting code, but for functions that are simple enough to be implemented in one line, I say go for it. We've got deadlines, people.

    --
    This author takes full ownership and responsibility for the unpopular opinions outlined above.
  47. Self Documenting by jamesh · · Score: 1

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

    Or to put some more straw in it "would you rather use a one-liner that requires 1 character of comments, or a 1 billion-liner that requires no comments".

    If your 1 line of code is so complicated that it takes 10 lines to write it out in a way that is easily understood, then 3 lines of comments is probably not going to do it justice.

  48. Reading comprehension anyone? by Anonymous Coward · · Score: 0

    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.

    Wow. You actually took the time to write that long a reply but didn't take the time to actually READ THE ARTICLE? This is how it starts:
    "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."

    So in response to that, you write: "Everything you know is wrong" because comments are important. So is reading comprehension.

    Even in the short piece that was listed it says this: "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?'".

    Now what does this mean? Hmm. Is he saying that writing 10 lines of code that doesn't need documentation is better than writing 3 lines of comments for one line of code? No. The "Myth" here would be that "Code must always be 'self documenting'". If that's a myth, then duh, he's saying code needs comments.

    If you read the actual article, I'd bet that you agree with everything the author says. But where's the fun in that?

  49. Bad programmer by Anonymous Coward · · Score: 0

    Just another bad programmer desperately trying to justify the bad job he does. I'll tell you what, you try working with a retard like this guy, and then try working with someone who "over-comments" his code, and see which is easier to work with.

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

    1. Re:Warning - war story ahead by Surt · · Score: 1

      Code was not less buggy. It's less buggy now, there's just a much higher multiplier thanks to superior developer productivity tools.

      As you said, 6000 lines, one bug.

      How many bugs do you suppose are in our 300 Million line codebase?

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    2. Re:Warning - war story ahead by Anonymous Coward · · Score: 0

      Yeah, but you could actually do something useful with 6000 lines of code in those days...

    3. Re:Warning - war story ahead by tengwar · · Score: 1

      The academic estimates I've seen for current code are in the range of one bug for every 20-40 lines of code. Mind you, I think that's very vulnerable to definition: if code doesn't do what the requirement says, theoretically that's a bug, but if there is no requirement separate from the code (the normal FOS case) you've reduced the number of bugs without increasing code quality. I think a more important point is that we used to be able to associate a bug with a line of code, or a region of the code. Now a bug is more likely to be something like "3G modem type XYZ indicates an invalid SIM after 20s of poor signal strength", and is probably not connected to a code error per se. If we allow that sort of definition, then based on the asymptotic decrease I see in finding bugs in a particular supplier's mature code over a couple of years hammering, I think about one bug per 300 lines is about right.
      BTW, I'm not sure what the 300M lines refers to. The total corpus in current use worldwide is way more than that. I've written about 100k lines myself for production code, and I'm sure there are more than 3000 programmers out there! Did you mean the source for Windows, perhaps?

    4. Re:Warning - war story ahead by Surt · · Score: 1

      No, I meant the codebase at my company, which is not MS.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    5. Re:Warning - war story ahead by Anonymous Coward · · Score: 0

      Soo, who else wants to know what 'midlertidig' actually means? Google gave me various pages that seem to indicate something like 'temporarily', heh. Might be wrong though.

    6. Re:Warning - war story ahead by tengwar · · Score: 1

      Ah. Well, of course I could tell you, but how much do you want to know the answer? [rubs thumb against fingers]

    7. Re:Warning - war story ahead by tengwar · · Score: 1

      No! Don't tell me! My life since then has been a spiritual search for the essence of "midlertidig" and its relationship to dexotrobing. An answer would be as objectionable as the experience of a zen monk finding that "one hand clapping" refers only to the self-congratulation of a pair programmer.

    8. Re:Warning - war story ahead by upuv · · Score: 1

      A lot more than you think that's for sure.

      Discovered bugs != Actual bugs

    9. Re:Warning - war story ahead by obarel · · Score: 1

      That's a lot of code!

    10. Re:Warning - war story ahead by vorpal22 · · Score: 1

      You are correct, as per Google translate. Note, though, that slashdot breaks the below link; you have to fix it manually. (Apparently | indicates an end of URL in slashdot logic.)

      http://translate.google.com/#da|en|midlertidig

    11. Re:Warning - war story ahead by Surt · · Score: 1

      It's a pretty decent sized company, which has been accumulating code for a reasonably long time at this point. It's all not necessarily active, but it exists.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    12. Re:Warning - war story ahead by Surt · · Score: 1

      Interestingly enough, we've had somewhere in the neighborhood of 100k defect reports. That's one per 3k loc. Factor in the undiscovered bugs and we're probably in the ballpark of the 300.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    13. Re:Warning - war story ahead by Speare · · Score: 1

      My favorite was a suite of FORTRAN programs written by X-Ray Crystallography lab chemists, sometime in the 70s I imagine, which were given descriptive names like CASTLE, FRODO and DRAGON. The code was laid in columns 1-71, and the FORTRAN compiler ignored anything after column 72 as a comment (a holdover from narrow punchcards). Thus, the authors wrote an epic fantasy story into the rightmost columns of 132-character lines. Every line of code had a bit of dialogue, action or other Tolkien-esque prose married to it. Folks in the lab in the late 80s hated changing anything in the code, bugs or no, because it would require fixing, reflowing, or stripping out the story column.

      --
      [ .sig file not found ]
    14. Re:Warning - war story ahead by SecurityGuy · · Score: 1

      20,000 lines of Fortran. Nearly all variables were i, j, k, etc, and it was rather complex modeling code.

      Comments? No, there were no comments. There was no documentation of any kind, unless you count the journal article in which the person who wrote the code described the model.

    15. Re:Warning - war story ahead by Anonymous Coward · · Score: 0

      A couple of dozen globals can make code hell. I really hope you don't ever need to fix (or change) software like that. It bloody _better_ work OOTB.

    16. Re:Warning - war story ahead by tengwar · · Score: 1

      And all of them were on the lines of "i9", "s9" - always a 9 for some reason. And yes, they re-used them for different purposes. Actually that made a small amount of sense, since it was loosely based on an older HP86 BASIC program, and re-using variable storage saved memory. However since the HP86 supported structured programming (now there's a phrase that takes me back!) there was no need for all the globals.

    17. Re:Warning - war story ahead by StormReaver · · Score: 1

      - 6000 lines of Pascal

      Oh, and one bug.

      [Adam Sandler drawl]Well, there's your problem.[/Adam Sandler drawl]

  51. Fun by Anonymous Coward · · Score: 0

    http://xkcd.com/156/

  52. You are so wrong and don't even realize it. by Anonymous Coward · · Score: 0
    I used to think like you do. Comments are not a panacea, aren't always required, and many times add nothing. Clear Code wins EVERY time. Yes, even with clear code, one should have some comments. Those comments should document the GOALS/WHY as briefly and succinctly as possible, of each Library, Module, Class, Public Method/Property (for API's that are meant for re-use -- if they're not meant for re-use, they shouldn't be public in the first place), THAT'S PURPOSE ISN'T IMMEDIATELY OBVIOUS BY THE NAME. The goal should be, to as much as possible, have the NAME of a method, function, or class be clear enough that adding a comment really doesn't provide much additional useful information. Who gives a shit if I give some really great explanation of what a method does and what its purpos is in comments in the class if everywhere the method is called it has a name like "catshit" (Yes, I've seen idiotic shit like that). So you're reading code somewhere that says something like:

    if ( xryagbg.catshit( flazugnb ) == 62914 ) {
    .... fuck load of lines of code ...
    }

    and then on the (WHAT CLASS, Oh, I have to look where "xrgagbg" is declared) I find that "catshit" has really nice comment explaining:

    When the sale amount exceeds our pre-set limit for the given plan, return a status code from the following: 12356 = DISCOUNT EXCEEDED, 62914 = DISCOUNT REALLY EXCEEDED, depending on the amount of excess as follows: blah blah blah...

    When, with properly designed code I could've had:

    if ( sale.discountExceeded( 500.00 ) ) {
    if ( sale.discountReallyExceeded( 1000.00 ) ) {
    this.processSaleReallyExceededDiscount( sale );
    } else {
    this.processSaleExceededDiscount( sale );
    }
    }

    I guess what I'm saying is is that comments will only be as good as the person writing the code no matter what. A lot of comments is usually a symptom of poorly written, unclear code.

    <RANT> ***** DAMN-IT WHY DOESN'T THE "ecode" TAG WORK PROPERLY??? **** </RANT>

  53. Why? by gbutler69 · · Score: 1

    Because expressing an algorithm recursively provides A LOT of clarity when the operation is in fact recursive. A proper language (like Scheme) that implements proper tail recursion this works really well. For other languages, its a fail due to the inability of the system to perform the calculation in constant space (due to pushing stack frames). That being said, most languages (including C, C++, Java) *could* be made to do proper tail recursion, then that wouldn't be an issue and you would be able to have the clarity of expressing a recursively solved problem with a recursive algorithm. Blame the problem on poorly written compilers and poorly implemented languages.

    --
    Over-the-top Response Guy! Giving "Over-the-Top Responses" since 1970.
    1. Re:Why? by Anonymous Coward · · Score: 0

      gcc and probably every other C compiler can eliminate tail recursion since ages.
      The only problem is that you better make damn sure that what you are doing really is tail recursion.
      I have no idea about Java, but in the worst case use gcj and it should behave the same as gcc for C.

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

    1. Re:Comments are useful by azgard · · Score: 1

      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.

      Interesting. You just compared the "no comments in code" movement with formalism movement in mathematics. Since the latter was a spectacular failure in mathematics, I can predict (and hope) the former will be a failure too.

  55. Proper commenting by elgee · · Score: 1

    Proper commenting is a blessing, not a curse. But I have noticed over the years that many coders need to learn proper grammar and spelling.

    “This are a funktion to comput the valu of pie”

  56. No. by gbutler69 · · Score: 1

    Unless it is an incredibly complex method (that should probably be broken up anyway) then the name of the method (in conjunction with the name of the class) as well as the names and types of the arguements, return types, and exceptions thrown, should be sufficient to tell you EVERYTHING you need to know. If not, you're not doing it right.

    --
    Over-the-top Response Guy! Giving "Over-the-Top Responses" since 1970.
  57. Asshole CS Professor by EmagGeek · · Score: 1

    I had a real asshole of a CS professor in college (who will remain nameless) who insisted that every single line of code be commented. He took 10 points off an assignment once because I didn't comment a line that only had a closed brace on it.

  58. Decommented by AlpineR · · Score: 1
    Here's some of my own code with the comments removed:

    uint32 randInt();
    uint32 randInt( const uint32 n );
    double rand();
    double rand( const double n );
    double randExc();
    double randExc( const double n );
    double randDblExc();
    double randDblExc( const double n );
    double operator()();

    inline MTRand::uint32 MTRand::randInt( const uint32 n )
    {
    uint32 used = n;
    used |= used >> 1;
    used |= used >> 2;
    used |= used >> 4;
    used |= used >> 8;
    used |= used >> 16;

    uint32 i;
    do
    i = randInt() & used;
    while( i > n );
    return i;
    }

    And here are the missing comments:

    Access to 32-bit random numbers
    integer in [0,2^32-1]
    integer in [0,n] for n < 2^32
    real number in [0,1]
    real number in [0,n]
    real number in [0,1)
    real number in [0,n)
    real number in (0,1)
    real number in (0,n)
    same as rand()

    Find which bits are used in n
    Optimized by Magnus Jonsson (magnus@smartelectronix.com)
    Draw numbers until one is found in [0,n]
    toss unused bits to shorten search

    v1.0 Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto
    Allowed for seeding with arrays of any length
    Added access for real numbers in [0,1) with 53-bit resolution
    Added access for real numbers from normal (Gaussian) distributions
    Increased overall speed by optimizing twist()
    Doubled speed of integer [0,n] generation
    Fixed out-of-range number generation on 64-bit machines
    Improved portability by substituting literal constants for long enum's
    Changed license from GNU LGPL to BSD

    Did you fully understand the code by itself? Are any of these comments harmful? Would anyone seriously rather have the code without the comments?

    1. Re:Decommented by Anonymous Coward · · Score: 0

      Well, they could be harmful in so far as that some of the time spent on writing them should have been spent on thinking up better names (I know I am really bad at it, too, but still).
      Or given these these functions
      > uint32 randInt();
      > double randExc();
      > double randDblExc();
      can you explain why "Dbl" seems to mean "exclude 0"?
      How does that fit in with the naming scheme used for randInt?
      "Both" would have been a lot less ambiguous and confusing in this context than Dbl, though it sure still isn't the perfect name.
      Why Exc instead of Exclusive?
      Why Int instead of Integer? Int could have meant interval as well if it wasn't for the documentation and function signature.
      These names sure would avoid a lot of possible confusion even without the documentation:
      > randInteger()
      > randExcludingUpper()
      > randExcludingBoth()

      And best of all:
      > Find which bits are used in n
      > uint32 used = n;

      which I think is a really bad variable name with a comment that does not help one bit in clarifying anything.
      Actually it confuses even further, because it uses the expression "bits used" as if it should be obvious what it means.
      A useful comment IMO would have been // ensure all bits below the highest set bit are set as well
      Personally I think a variable name like "flood" or "fill" would have been preferable, but I admit that that's very disputable.

      So I boldly claim that you have proven that sometimes the reason you need comments is because your code is not as good as it could/should be ;-)
      (and I hope you don't take this personally, the code is not particularly bad, but adding comments is not necessarily the best way to make code better or better to understand).

  59. Na, it isnt, we just disagree by omb · · Score: 1

    Hopefully the Internet Archive and Google will fix the 'out of print' problem.

    Programmers, who cant, should not touch complex code, and NO amount of commenting stops them (fixing) it from right to wrong. If you dont know you should not fix code cos it looks wrong, I would cut your coding finger off. If you make any change to a complex algorithm you have to review/debug it ab initio.

    Read a lot of Linus (Tovolds) comments about code, reading source, and what NOT to do and you will learn a lot. If you want to be a good programmer follow good examples eg Prof Sir Peter Swinerton-Dyer, Prof Tony Brooker, Dr Martin Richards, Edsker Dijkstra, Prof Don Knuth, Marc Andreeson, Linus Tovolds (for a few examples). A really good example is the early evolution of Git, when Linus was the prime implementor, it was awsome.

    By reading good code you lear a lot, but if you ambition is to be a typically under-educated US code-droid, dont bother. Code, like lierature, should not be limited by essentially illiterate readers,

    I do like your sig though, very true.

  60. Principles Over Rules by ed.markovich · · Score: 1

    There's a quote in Code Complete ( I think ) that one should be able to read code in the evening in one's armchair with a glass of brandy as if it were a novel. My personal version of it - and the criteria I impose on my team - is that I should be able to read and understand the code w/o having to think too hard or knowing much about what the programmer is trying to do. It's really easy to enforce this in code review - if I can sit at someone's desk and quietly read their code and know what's going on, it's good enough - either sufficiently-commented or self-commenting. On the other hand, if I have to ask what a section does, whatever the developer says to me verbally is also a good candidate for a comment. The other key factor in commenting is that it must be clear not only what the code is doing, but why. For example, if I encounter the following in the code: if (productType != SOME_TYPE and client != SOME_CLIENT) { sendReportToCleint() } it doesn't help to have a comment saying // Send the report, unless it's SOME_CLIENT buying SOME_TYPE. I already know that... what helps is // Don't send reports to SOME_CLIENT for SOME_TYPE because their system // crashes on this message and they don't know how to fix it. This is // as per discussion with Jon Doe on mm/dd/yyyy This is basically the principle of least astonishment

    1. Re:Principles Over Rules by ed.markovich · · Score: 1

      Ugh sorry. Foiled by the HTML formatting. Here's what it's supposed to look like

      There's a quote in Code Complete ( I think ) that one should be able to read code in the evening in one's armchair with a glass of brandy as if it were a novel. My personal version of it - and the criteria I impose on my team - is that I should be able to read and understand the code w/o having to think too hard or knowing much about what the programmer is trying to do. It's really easy to enforce this in code review - if I can sit at someone's desk and quietly read their code and know what's going on, it's good enough - either sufficiently-commented or self-commenting. On the other hand, if I have to ask what a section does, whatever the developer says to me verbally is also a good candidate for a comment.

      The other key factor in commenting is that it must be clear not only what the code is doing, but why. For example, if I encounter the following in the code:

      if (productType != SOME_TYPE and client != SOME_CLIENT) {
         sendReportToCleint()
      }

      it doesn't help to have a comment saying

      // Send the report, unless it's SOME_CLIENT buying SOME_TYPE.

      I already know that... what helps is:

      // Don't send reports to SOME_CLIENT for SOME_TYPE because their system
      // crashes on this message and they don't know how to fix it. This is
      // as per discussion with Jon Doe on mm/dd/yyyy

    2. Re:Principles Over Rules by ed.markovich · · Score: 1

      The logic error is intentional ;)

    3. Re:Principles Over Rules by donutzombie · · Score: 1

      Exactly. I can always figure out the "What's it doing?", but in many cases, "Why did s/he do that?" is forever lost.

      --
      -- Dear God, please save me from your followers.
  61. Comment first by MrKaos · · Score: 1

    I actually comment the main parts of my code before I write the code. Reason being is I like to get the general layout of the code down first and then add further comments as I go along to explain my reasoning *to me*.

    I don't know how long it's going to be before I come back to a piece of code and nothing annoys me more than having mental clutter in my mind. I don't want to have to *remember* what why or how certain bit of code does what it does. I just want to pull up my code and explain it to myself and say "thanks me of the past for considering me today". Coders that don't explain what they are doing in their code are just hard to work with.

    Well commented code helps code look beautiful and flow like poetry. When you look at code you can see almost immediately if it is going to be painful to modify. I try to put as much back onto the machine as I can, like using database design tools so I don't have to keep stuff in my mind.

    I use Nassi-Shneiderman mixed with pseudo-code on paper to do a design (I'm getting better at UML tools - so soon I hope to upgrade this part of my coding practise) and when I'm happy with that I move to comment before writing the actual functional parts of code, increasing the detail of the comments as I go along. I used to be shy about my code but now I'd be embarrassed if I didn't comment my code - because it's not polite to my colleagues. Comments mean I don't have to waste time trying to remember where I was up to as it's simple for me to compare it with my design and away I go.

    --
    My ism, it's full of beliefs.
  62. My Real Problem ... by smpoole7 · · Score: 1

    Isn't the lack of comments, it's getting lost in a dozen (or two or fifteen dozen) different source code files, trying to figure out what the original programmer wanted to do. F/OSS is a beautiful, wonderful thing, and I'm fully committed to it, but I can't tell you how many times I've downloaded a F/OSS project with the intention to tinker with the code, only to get completely lost in it.

    Just for record, I'm a commenter, and I like comments that explain what the code is doing. But to help address the aforementioned, my code contains lines like "SomeFunction() /* see doodat.h */" and "function( SOMEVALUE ); /* see heredat.h for SOMEVALUE */" because I know that even I, the guy who wrote the stuff, will come back years later and be totally lost.

    If I had a dollar for every time I've grep'd for the main() function, then followed the execution thread just to see what a program was really doing, I could take us all to dinner. :)

    --
    Cogito, igitur comedam pizza.
  63. The Commentator by EatAtJoes · · Score: 1

    So far as I know there's no automatic system that will generate the comments that the author failed to put in

    you've obviously not heard of The Commentator ...

  64. Tbis is why COBOL is the best... by cts5678 · · Score: 1

    language: it's self-documenting code.

  65. Good Comments Are Good by Greyfox · · Score: 1

    I've seen some well commented projects where the code comments were really the only thing you could read to get a handle on the business logic behind the application. Occasionally you'll read a comment and realize that the original programmer had a misconception about how the next bit was actually supposed to work. Maintenance programming is as much about understanding the state of mind of the guy who wrote it originally as it is about writing code.

    --

    I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

  66. It depends on the quality of the comments by MartinSchou · · Score: 1

    As others have said, if the comments are along the lines of

    i++;//increment i

    then it's just complete rubbish.

    What I would like to see though, is some very complicated encryption algorithm with and without useful comments (useful being the why). See which of them are easier for the average developer to get a grasp of.

  67. Seperate code and comments in one file. by Anonymous Coward · · Score: 0

    I have a unique system for code comments that serves my own projects incredibly well.

    I find that comments break the flow and readability of the code, especially when there are huge blocks of comment for a small section of code.

    What I've done is set the tab size to 85 characters in my editors. I do not use tabs (one because I prefer 2-space indenting, two because most editors have Smart Tab features), so to comment a line, I tab at the end of the line and add as long as a comment as I want about the line there.

    On a widescreen monitor, this makes both code and comments visible (up to 90 characters of comment on my 1440-wide screen), without one breaking the readability of the other.

    Some other developers I've worked with have liked the system so much they started using it as well.

  68. Re:Not commenting is a sign of not thinking or car by Anonymous Coward · · Score: 0

    that's a whole lot of free-floating ad-hominum based on
    the shaky generalization that every class or public method
    needs a comment.

  69. Why it does it and not what it does by clay_shooter · · Score: 1
    Too bad 5 is the top mod Score.

    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.

    Why is this so hard to teach developers? My last 3 projects had minimum documentation standards that developers always had trouble with. They would just add comments that said what the code did. We usually don't want comments that describe what the code does. We want to know why the code does what it does did that. "bug report foo said the exception exists because" or "Law X in state YY requires this behavior different from other states".

    The exception is of course the hot shot developer who does all kinds optimizations or algorithms beyond the reach of most of the team. We can't always stop them from putting that code in so we force them to describe what it does.

  70. StyleCop by Saint+Stephen · · Score: 1

    I do mostly C# + SQL, and have gotten into using StyleCop since it came out. It forces you to use xml comments on every method, field, property, public or private. For properties you have to use "Gets or sets the value of Foo" or "Gets or sets a value indicating Foo" (for bool). Since the only duplicate comment allowed is "The parameter is not allowed," what I do is fill in by default ALL the comment parts (summary, param, returns) with "The parameter is not used."

    Then I get my code to be StyleCop clean, and go back and search for "The parameter is not used." I update the comments appropriately.

    For comments in the body I use "// TODO refactor" or something terse. I find putting SOME comment block on everything makes it nice and readable, and if I see a huge block of stuff with "The parameter is not used." I know it's something that's not important to comment (like a million TextBox field declarations), or else it's somethign important I haven't gotten around to commenting yet.

    So this is working all well for me :-) The gist is I use the StyleCop guidelines, a boilerplate for "no comment comments", and terse inline things usually indicating work items in the body.

    Works for me and I explain it to the next guy and he can figure out my intentions. Right balance of anal retentiveness and terseness for me.

    1. Re:StyleCop by dcam · · Score: 1

      That style of commenting is one of the worst in existence. Most of what you have mentioned is immediately legible from the code, or even hovering over with intellisense. It is also creating a rod for your own back, those comments have to be maintained with the code.

      Bad idea, while it looks enterprisey it don't think that adds anything to the code.

      --
      meh
  71. Rewriting code is often out of the question by clay_shooter · · Score: 1
    A rewrite involves risk and often breaks existing functionality. It's hard to explain to the business whey they went down at $10,000 hr because some developer thought they understood what a module did and "fixed it". I personally believe that we need to recast the code that no one on the team understands the testing expense and risk have to be explained to management.

    I had this discussion with some mainframe folks a couple weeks back. They never rewrite code. They don't understand what all the code does so they always wrap existing code with new code when adding functionality. Sometimes the new code just stops the old code from executing in certain situations.

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

  72. Re:Not commenting is a sign of not thinking or car by JoeMerchant · · Score: 1

    When your public method is named something like initCamera( int camID ), or grabFrame(), I'm not altogether certain what's gained by spelling that out in a comment... maybe if there's something deeper going on, but if it is as simple as it looks, why pollute it with additional words to read that convey the exact same meaning?

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

  74. "Thus, I would choose to write the comment..." by Frankenshteen · · Score: 1

    "In most cases" That's the bottom line - just apply the same rule to comments you do to code; overly verbose is usually more confusing.

    --
    "It's a doughnut stuffed with M&M's. That way when you finish the doughnut, you don't have to eat any M&M's."
  75. Lengthy legalese... by FriendlyPrimate · · Score: 1

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

    You know....for many of us developers, this legalese is dictated by company lawyers. We can't simply "avoid" putting this legalese in our code.

    1. Re:Lengthy legalese... by omb · · Score: 1

      Yeh you can, put the CRAP in COMPANY_LEGALESE_JUSTIFY_OUR_EXISTENCE_AND_BILLINGS.txt file and cite (nice legal word) the file in the 1-liner just dont defacate the crap everwhere, keep the shit contained. What the lawers dont want to tell you is that you need the

      Copyright (c) YYYY-YYYY, Holder, (license if any) --- in each file of code you wish to protect. See Bern Convention. In the US you MUST also REGISTER the Copyright but that dosnt apply in Europe or Asia.

  76. Do it in blocks by phred75 · · Score: 1

    Unless I'm coding some high speed spASM code... In regular C/C++ I stick to commenting a whole block as opposed to each line. I've worked with overly anal coders who code each line.. I want to kick them in the teeth.

  77. Comment removed by account_deleted · · Score: 1

    Comment removed based on user account deletion

  78. Comment on no comments... by CFBMoo1 · · Score: 1

    I hate uncommented code, I hate it with a passion. I hate having to track down how this or that works with no comments or documentation to figure something out. I hate hearing people say, "The code is the documentation!" because I just want to slap them silly.

    I comment my code, whenever I make changes I damn well do my best to document those in the code and developer guides I usually write for projects. I figure if nobody is going to be kind enough to me and leave good documentation and code comments then I should set an example. Thankfully at my current job, the last developer to retire left such good documentation I'm in heaven and even tried to clean up my documenting methods more based on his work.

    --
    ~~ Behold the flying cow with a rail gun! ~~
  79. Sam I am! by DomNF15 · · Score: 1

    I like the comparison to literature and how it illustrates personal preferences, but respectfully disagree with the idea that literature will all eventually converge into very short, efficient, single purpose works. The entire point of literature is to convey some theme(s) through the medium of a story. Stories are not meant to be efficient or singular in purpose or meaning, necessarily. When you read a book, you are along for whatever ride the author wishes to take you on. And it is exactly that ride, not some re-factored or boiled down version, that he/she wants to experience. If you've ever read Cliffnotes instead of an original text, you'll understand. I don't think all literature needs to be more "readable", sometimes it's ok for something to be a little beyond your comfort threshold, it makes your brain work just a little harder, and I think that's a good thing. Unless of course you want all books to read like Green Eggs and Ham :-)

  80. I have to disagree. by hallux.sinister · · Score: 1

    I would rather use code with 1 line of high-level language, requiring three lines of comments, than 10 lines of high-level language code, with no comments, because 99% of the time, the MACHINE is what's going to be reading the code, in compiled binary form. At compilation time, as I think everyone on /. knows, (or should) all those comments get sent Express Mail to /dev/null, and the result is usually more compact final-product machine code, which executes faster, using less time and processor power. The other 1% of the time, when it is I who am actually looking at it, I don't mind reading a few sentences from the previous coder telling me what he was TRYING to accomplish with that function.

  81. The biggest misconception he forgot to mention... by Anonymous Coward · · Score: 0

    Lots of comments doesn't make bad code good.

  82. The Elements of Programming Style by ajcarr · · Score: 1

    For heaven's sake, just read:

    Kernighan, B. W. and Plauger P. J. (1978) The Elements of Programming Style, 2nd edn. McGraw-Hill

    They deal with commenting and its pitfalls perfectly adequately.

    1. Re:The Elements of Programming Style by will_die · · Score: 1

      Also Code Complete for a little updated stance.

  83. It's program *structure*, not language features by jonaskoelker · · Score: 1

    Object-oriented languages in general require less documentation since good design and properly named methods and properties do document things relatively well.

    I think it's the object-oriented program structure, not language features, that makes things easier to understand. And only where that structure makes sense.

    For example, have a look at Simon Tatham's puzzle collection. It's object oriented C code, with excellent developer documentation.

    There's an interface "Game", implemented by Sudoku, Minesweeper, etc., which basically defines all of the game.

    This interface and the interfaces it can talk to are all documented outside of the code. Each of the implementations have comments in the code explaining the implementation.

    Class-level documentation is much more important than documenting the details of the methods themselves.

    More important---they're more useful towards which end, exactly?

    You bring up Java. I find that in java, whenever you want to pass around a method, you have to duct tape it onto a class and instantiate that. See for example Comparator; really you just want to pass a comparison function to the sort method.

    This tends to introduce "spurious classes"; classes that you have to create because of constraints in your language, not because they're the logical way to organize your program.

    In those cases, I think it's much more important to have good higher-level architecture documentation; "these are the classes involved in setting up a network connection. Here's how they relate. Here's the order in which you instantiate them, and the methods for doing so."

    I think this springs out of a good usability idea: have the user's (programmer's) task in mind. Instead of documenting the tools `find' and `grep' and `locate', document the process of searching for your stuff.

    Instead of documenting the Socket and Packet classes, document the process of shoving bits onto the wire(lesse)s.

    Perl and C code, on the other hand [vs. Java and .NET], can be unmaintainable even with a number of comments, because the old functional design is not easily maintainable.

    Again, it's program structure, not language features. You can implement most structures in most languages (except maybe B&D Pascal, but hasn't Pascal become less B&D over the years? I haven't kept up).

    A minor nit: ML/Haskell/Lisp programmers might not agree with your choice of the word "Functional". They'd call the paradigm procedural; I don't know if there's consensus about which word to use for the typical designs, if there are typical designs. In any case, there's no "The" way to design C/Perl programs. Oh, and perl is OO nowadays.

    Consider rewriting these in a more modern language.

    Consider understanding the capabilities of the less modern languages and the restrictions of the more modern languages.

    I'd instead recommend refactoring the code instead of changing languages. It seems like something you could do faster and cheaper. Hey, I just saved our department more money than you did :P

  84. "Midlertidig" means temporary by jonaskoelker · · Score: 1

    - 1 comment - the single word "midlertidig"

    FWIW, "midlertidig" means temporary. My guess is that it wasn't used for a local variable in a `swap' method ;)

    1. Re:"Midlertidig" means temporary by azgard · · Score: 1

      Perhaps it was written at the beginning of the program, indicating that it is a quick temporary solution, to be replaced by something better in the future. That would explain why there are no comments in the first place.

    2. Re:"Midlertidig" means temporary by tengwar · · Score: 1

      Nope, it was a commercial product. And GP is correct - it wasn't used as a swap or other temporary.

  85. has anybody noticed... by Anonymous Coward · · Score: 0

    that the people against commenting sound like they've worked in environments where they were forced to write comments

    and the pro commenting people sound like they've been struggling through some poorly commented and hard to read stuff.

    It's about balance.
    Some comments help a lot to make code more intelligible.
    Some is pointless noise.(ie //increment x)
    A lot would not be necessary at all if the code was sensibly structured, with good variable names

  86. Examples would help both sides of the argument by Anonymous Coward · · Score: 0

    Software development is a broad enough topic to make this discussion difficult without examples.

    http://code.google.com/p/virtualagc/source/browse/trunk/Comanche055/CM_BODY_ATTITUDE.s?r=258

    http://c2.com/cgi/wiki?CommentExample

  87. Re: OP by Anonymous Coward · · Score: 0

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

    What defines 'requires no comments'? To me a comment is useful if it saves someone (me or anyone else) time later. Even if you have a brilliant and fairly self-documenting 10-liner, what is quicker for a programmer: reading a one line comment or reading 10 lines of code? What about a poor scripter that is using a c/c++ function from a simpler language that may not be able to decipher the original code at all, no matter how 'self-documenting'.

  88. Questions by presidenteloco · · Score: 1

    Is it ok to call initCamera possibly multiple times, because I don't know if it is inited already?
    If not, how do I tell if the camera is initialized?

    What is a frame? What is a frame a part of? Where did I grab it from? Where is the data
    that I presumeably grabbed this frameworth of. i.e. where did I grab it to? In what format is it
    represented? How much processing does it take to grab a frame? A trivial amount? Or can
    I have my code call grabFrame 1000 times a second?

    I guess that stuff was all obvious from the names.

    --

    Where are we going and why are we in a handbasket?
    1. Re:Questions by Anonymous Coward · · Score: 0

      It's not the job of comments to teach you everything about the problem domain.

    2. Re:Questions by JoeMerchant · · Score: 1

      In my example case, initCam is a wrapper for the OpenCV cvInitCamera function, with just enough support to make it work in my app - same for grabFrame() - so, I could reproduce the library documentation in my code, or just rely on the next programmer to see the cv calls in the function and look it up himself.

      Your copious examples are more or less what I referred to as "something deeper".

  89. CommentsAreSoLastCentury. by shutdown+-p+now · · Score: 1

    IPreferToUseDescriptiveButLongIdentifiersInstead(ForBothFunctionsAndVariables);

    YesInCaseYouDidntGuessILike(Java,CSharp);

    1. Re:CommentsAreSoLastCentury. by bill_mcgonigle · · Score: 1

      YesInCaseYouDidntGuessILike(Java,CSharp);

      Consider moving many of your comments into exception error text. It's good for users and doesn't get refactored out of scope.

      --
      My God, it's Full of Source!
      OUTSIDE_IP=$(dig +short my.ip @outsideip.net)
  90. Literate Programing by os2fan · · Score: 1

    Don Knuth described Literate Programming in which the program is embedded in comments, one using a preprocessor to write the program. The preprocessor runs as a command processor, using the source as a batch file. One gets a properly sorted batch file as output. Because of this, one can overcome limitations of the programming language, use pre-processor variables etc, and produce several linked files etc.

    Documentation is relatively straight forward, since one writes what one wants to get, limitations, API and examples by way of a wish-list, and then create the routines that make this happen. You can write a tight section like "File I/O", for fileopen() and fileclose() along with getline(), putline(), etc, without exposing the filenames to all of the subroutines. I've written a program to write Web pages in it, for example, http:\\www.os2fan2.com\pgloss\index.html and its attendent pages. It's pretty elegant really.

    The temptation of LP is to use it to solve a problem per source, a note that Jon Bentley (Pearls of Programming) noted. LP is about sorting problems: however, the sort of problems that Knuth sought to solve are complete things in an educational setting, not bits of problems in the real world. None the less, I use it to write terse batch files etc, where the LP source is the help file too.

    --
    OS/2 - because choice is a terrible thing to waste.
  91. Re:Not commenting is a sign of not thinking or car by Anonymous Coward · · Score: 0

    One of the places I worked at extended the "no comments" rule to "no Javadoc, no documentation except on the Wiki". Of course, once the code is passed to another company the Wiki won't be (since it was blocked from customer sight it will be considered "company confidential") and there will be absolutely nothing to tell the next group how to change anything. The same project engineering head said that since this is an Agile project there should be no design documentation (at all).
    The only answer for this is "comments are evil". I gave up and removed my comments (he typically changed code without consulting the programmers anyways).
    This is what the "comments are evil" line gets you if handed to morons.

  92. Doxygen rules by Anonymous Coward · · Score: 0

    We have to meet formal documentation requirements. (FIPS 140-2, Common Criteria).
    Doxygen makes that a breeze - the documentation in the source isn't particularly readable (but not useless either), being able to annotate the sources and produce the documentation you have to have with the push of a button is great.

    It has improved code quality and found a few bugs as well, but that's a long term gain not short term -i.e. if the call tree's look like spaghetti it's probably clean up time.

    All in all - taking the long view (several years), it's been a massive gain. Short term, it's a looser - it eats time putting good docs in place - so for most software companies - where "push it out the door" seems to be the rule, you aren't going to be winning.

  93. Both Sides by Anonymous Coward · · Score: 0

    I've worked on both ends of the spectrum.

    In my first job out of college, the boss was an old school C programmer who was beyond hardcore about his coding standard. The code not only had to be commented (with a comment on EVERY SINGLE LINE), but also properly formatted. What's the difference between:

    }//for numPoints

    and

    } // for numPoints

    If you said, "Having the boss yell at you for five minutes." you win the prize. I'm not kidding or exaggerating.

    -----

    My current job is very lax. If the code works, it doesn't even matter if it's been run through an obfuscater.

    Of course, if something is wrong with the site, then I (or my co-worker) better be able to fix it -- quickly.

    So, either write it 100% perfect the first time, or keep the non-obfuscated code around; keeping the site working as expected is the *only* thing that matters.

    -----

    As a software engineer, I prefer the rigor of the first. (I can do without the yelling, though.)
    As a code monkey, I prefer the pragmatism of the second.

    Maybe my next job will put me somewhere in the middle.

  94. Comments dont help with other peoples code by keean · · Score: 1

    As someone who frequently gets asked to work with code written elsewhere, adding features, fixing bugs etc, I find comments in code mostly useless. Reading and understanding the code is the only way to really understand what is going on. I find the comments don't really save time, as if there is a bug in the code, the original programmer did not understand the code anyway.

  95. Code review failed. Please resubmit by baileydau · · Score: 1

    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 // <-- But you forgot to comment the meaning of this line!!! Please redo and resubmit to code review

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

    --
    Ever stop to think ... and forget to start again?
  96. Troll indeed by mrjb · · Score: 1

    "Comments aren't actually executable code, therefore they aren't maintenance costs, right?"

    Absolutely right, yes. Although comments also need to be maintained when the code is updated, their maintenance costs are negative, because they SAVE TIME (That's why they were invented)!

    The same goes for other forms of documentation- some code would not only take *more* time to maintain without documentation, but would simply be impossible to maintain without it.

    "Comments make code more readable."

    Yes. Not all of them, but when used properly, they damn well do. Example: If there is a 'magic number' in the code, a comment can help explain how the author arrived at that magic number, and allows the next developer to change the magic number to another value as needed. Without the comment, this would be impossible.

    Another example:

    unsigned long lastsectornum()
    {
    if (!(this->foundlastsectornum))
    {
    // cache result.
    this->m_lastsectornum
    =lookuplastsectornum();
    this->foundlastsectornum=true;
    }
    return this->m_lastsectornum;
    }
    I'd say in the above example, the two-word comment makes it a lot more clear what is going on.

    "You should comment every function, method, class, and module"

    Jason goes on to use this as an example:

    def get_x(self):
    """
    This method gets x.
    """

    That's simply a bad comment, but it doesn't invalidate the statement. We still want a comment there- one that explains what 'x' is. Without comment, there is no way to tell. The problem here is not that there *is* a comment, but that the author (in this case Jason) wrote one without added value. For any function with parameters, however, we'd want to know what upper/boundaries they have.

    def get_x(self):
    """
    Returns horizontal pos. of the mouse cursor
    """

    See, this is much clearer! (though arguably, the method name is wrong and the comment unnecessary). There's still a use for a comment here: What does the method return if no mouse is present? Is it the responsibility of the method to check for this, or is it simply not allowed to call the method in such cases? Comments to the rescue once again.

    "Code must always be self-documenting"

    Jason calls this a myth as well, and this time I have to agree with him. Although we should strive to make our code as clear as possible, it *can* not always be self-documenting. Comments were invented to solve that (see above).

    However, "In most cases, comments should be viewed as code smells." is utter bull. Jason should spend a few years writing assembly language. Perhaps then he'll learn to value comments for what they're worth. Personally, I have a strong feeling I wouldn't want to maintain Jason's code, as he feels that he need neither document his code nor write self-documenting code.

    --
    Visit http://ringbreak.dnd.utwente.nl/~mrjb/growingbettersoftware to download your free copy of the book
  97. Self documenting code by Anonymous Coward · · Score: 0

    Self documenting code is a desirable side effect of a clean coding practice that has something more in mind. Writing very 'verbose' code is like drawing a precise picture of the analysis of the problem the code is supposed to solve. It 'tells you a story' of divide and conquer. This serves you so much when it comes to bug fixing or more important: bug preventing. And it gives you an extra level of reflecting about what you're actually doing.

    To many programmers such a discipline may seem like talking to little children and explaining each and every bit of obvious information. I had the experience to get bad grades in my math tests because i thought myself to have good memorizing abilities so i preferred not to note too much intermediate results. That's where I discovered my psychology of introducing bugs.

  98. Something like this ? by FrankDerKte · · Score: 1

    /*
      * Sorry, had a couple of beers and no time to fix it, yet ...
      */ // Crappy code here

  99. Try to write undocumented code with Perl by freaker_TuC · · Score: 1

    Since I'm using remarks in my code, my coding has increased double in speed.

    for loops, a missing bracket can be easy defeated by adding a code remark behind every closing bracket.
    In big sources, this is a convenience to see where exactly a subroutine has finished to its result.

    Not only for loops, but also repetitive code, regexpes (which you can write in more than one way) and parameters will give a lot more meaning when having a little bit of documentation; even, if not for the next programmer.

    I could not imagine an architect or anyone who builds buildings would be not making *any* sidenotes about their project.

    --
    --- I am known for the ones who want to find me on the net. Is that a privacy risk or a privilege? One might wonder..
  100. "High level" comments by JSBiff · · Score: 1

    I kinda know what you mean, but there's been times where I've been working in a block of code, written by someone else, where a short, very-high level comment about what the code, in general, was *supposed* to be be doing, would have helped out a little bit. But, you say, can't you tell what the code was supposed to be doing from a) the function name, and b) the code itself? Well, IIRC, the function was ambiguously named, and the code was broken - the code wasn't even correct, hence the reason I was working in that block of code, trying to fix it, but it wasn't clear what the code *should* have been doing, from a high level.

    I mean, I still wasn't completely stuck. I knew the code wasn't working, and how it was effecting the rest of the program, so I *was* able to kind of work backwards from the rest of the program and make a good guess what the code probably should do, and just kind of worked from there to get the desired results that would make the rest of the program work. But, a one or two line comment from the original code author might have helped save some time.

  101. Who??? by will_die · · Score: 1

    The only Jason Baker of note is a football(American) punter.
    So are the submitter and the author the same person and this is just a 15 seconds of fame?

  102. asymptotic time complexity by microbox · · Score: 1

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

    There is an important caveat to this -- although it might be obvious. You *always* design and code with awareness asymptotic time complexity, and sometimes space complexity. If you just think "optimize later", then you might be doing a root canal on your code.

    I only say this because there are so many developers who have no idea about how to use algorithms and data structures.

    --

    Like all pain, suffering is a signal that something isn't right
  103. There's no "myths" here... by QuietLagoon · · Score: 1
    Just someone trying to create a news story.

    .
    The reality is that there are good comments and there are bad comments. Good comments are helpful, bad comments are not. I forgot to mention that there is a third type of comment, the evil ones. The evil comments are wrong, leading subsequent programmers astray.

  104. code completion by Anonymous Coward · · Score: 0

    Two words: "Code Completion". Many IDE's (like Netbeans) use PHPDoc comments to make educated guesses about code completion. A one-liner function with 5 lines of comments is worth it.

  105. I'm a fan of [useful] comments by eggy78 · · Score: 1

    My employer has a very large, and, IMO very organized, but incomprehensibly so, codebase. There aren't a lot of high-level specs, and there aren't a lot of good comments in the code. There are a lot of times where I will be tasked with finding a bug, and I can see where the program breaks as well as why it breaks, but without knowing what it's supposed to do, it's hard for me to make the right fix. There are a lot of places where we have some 1500-line (don't even get me started on this) C++ function handling some enormous data structures (20+ member variables, of which roughly half of those are equally-large data structures) and there's basically no info on what any of it is really supposed to do (other than whatever function/variable names there are).

    Whenever I'm not cleaning up other peoples' messes, I tend to focus on making sure it's obvious what I was trying to do and that the input/output of my function is well-specified, so if someone comes along behind me it's easier for them to locate the "true" problem by looking at the specifications than just finding a "problem" and trying to make sure it doesn't happen again with some quick fix. I also try to keep my functions as task-specific as possible and small enough to be somewhat comprehensible on their own while considering that we don't have unlimited stack space on our devices.

    But, then again, I'm relatively new there. They might break my will eventually...

  106. Real world code and programmers please ... by Anonymous Coward · · Score: 0

    Very clean and easy code ... No comments required ... Obvious ...

    Okay then, without looking this one up on google or fishing from your CS books etc. Please explain this simple piece of code.

    int n = (count + 7) / 8;
    switch (count % 8) {
    case 0: do { *to = *from++;
    case 7: *to = *from++;
    case 6: *to = *from++;
    case 5: *to = *from++;
    case 4: *to = *from++;
    case 3: *to = *from++;
    case 2: *to = *from++;
    case 1: *to = *from++;
    } while (--n > 0);

    Also some very nice ways of counting bits in a variable, traversing lists, sorting arrays etc. Very neat and clean code samples can be found on the internet I challenge every one to explain some of the 'cool' samples you find without reading any comments on it.

    So here is the deal:
    Professional code base == years of development and tons of business logic from tens or hundreds of different developers with > 1 million lines of multi-threaded code. So you're telling me that all you need is to look at the code base and you immediately understand the full extend of every line of code you read ?
    Have you ever looked at code from India or at code from a freshmen ? Have you ever tried to re-factor functions with 6000 lines of code or more and source files with > 60.000 lines of code with directories of more then 500 source code files ?

    If this is so and you can naturally fix all bugs in these multi-threaded morass of code, I would like to interview you for a position at our company and am willing to pay you more then any other offer you currently have.

    You are talking about hypothetical code that does not exist in the real world unless the code base was written by only one person. And even then. Point in case, we have a cool library that is at the core of our multi-threaded application base. Written by one guy. No comments. Very clever, dense code. So clever in fact, it is unreadable for any one but this guy. So lets assume he is mortal and / or he decides to leave the company at some point in time. I am sure you have no issues to re-write the code base that is at the center of a whole companies product line and makes the product stand out from any one else's product. Or you have no problems figuring out all the bit shifting etc that is taking place with mutex's and pthread calls all over the place in no time at all and fix problems in a matter of minutes.

    BTW, the same guys who say source code comments are useless also ignore compiler warnings and are the same type of people who insist they can re-write a whole application suite in a matter of weeks that has taken a team of 10 multiple years to write ( usually because they are too lazy to read and understand the code ).

    I could go on, but I am so upset with this article I better stop here.

  107. what about bugfixes? by Anonymous Coward · · Score: 0

    A project is not just about the codebase anymore: now we've got issue tracking
    systems and (D)VCSes ruling the day.

    Seeing your code as something independent is foolish for anything but the
    smallest toy-ish project.

    I like something like:

    bugfix for issue ${your-favorite-bug-tracking-system-bug-number here}

    or even:

    bugfix for issue ${your-favorite-bug-tracking-system-bug-number here} introduced in changeset 5b8362e108fc

    Should you ever change from (D)VCS (Mercurial here), you can write a script to automatically update
    all the changesets reference.

    That's how they do it in "Real-World[TM]" millions-and-millions line of code projects
    where you need both the code and references to discussions / bugs description
    concerning said code.

    The OpenJDK comes to mind.

    Millions and millions of lines, I tell ya, you should listen kids ;)

  108. Reviewers are to blame as well for poor comments by CaptCanuk · · Score: 1

    I work in an environment with 30 developers, 400K SLOC and 2 global sites specifically for one component (in a family of 12). Our review process is pre-submit and done through e-mail. Reviewers are as responsible as the code submitter in identifying negligent comments. From the check-in comment, the intent of the change should be obvious; the comments need only support the intent. Asking someone to review a change before submission has the added benefit of ensuring at least two minds understand it (even if one is only cursorily). If you don't understand the code, you ask questions and ensure each question answered results in a architectural document change, code change, comment change, or at the very least, check-in comment change. Sometimes, it is not apparent to the submitter that his concepts parlayed into code are consumable by others. It's for that reason it is important to put in bad code sometimes to see if people are paying attention.

    --
    ---- The geek shall inherit the Earth.
  109. Only a neophyte would post this drivil by bwanagary · · Score: 1

    Well, all I can say is that "Empty vessels make the most noise."

  110. Do you know the pain... by SharpFang · · Score: 1

    ...when you wrote 3 lines of code that required well-deserved and richly written 20 lines of comment to explain how they achieve their purpose, and then a change to project makes them obsolete and unnecessary?

    OTOH there's still a piece in my major project // uchar reverse_det_ndx[MAX_PROG][MAX_FAZ][MAX_DET][MAX_DPF+1]; // TODO: Recall, what did I need this for.

    --
    45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
  111. Obligatory... by SharpFang · · Score: 1

    code:

    for(unsigned char x=limit; x>=limit; x--)
    {
    do_something_with(x); // no comments whatsoever
    }

    Direct result: my fingers tightly locked around throat of programmer who wrote that.
    Indirect result:from then on, whenever he purposely uses variable overflow/underflow, he always comments that he does.

    --
    45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
    1. Re:Obligatory... by SharpFang · · Score: 1

      ...also: there are four legal endings to a case statement.

      • case (only if no other content was used between the two)
      • break
      • return
      • //fallthrough

      Anything else is a syntax error.

      --
      45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
  112. Code Complete by minstrelmike · · Score: 1

    Best book on coding is Code Complete. Also has the best advice on comments.
    If the variables and functions are named AND USED correctly and
    you don't comment on standard procedures open(fname) // open filename
    then there is very little that needs commenting.

  113. No Comment by Rambo+Tribble · · Score: 1

    It needed to be said.

  114. pretty large pile of misconceptions by Uzik2 · · Score: 1

    In my long career I've never heard anyone advance the first two arguments, and only one manager ever required we comment every function. This guy must have just had a difficult time finding something to blog about if this is all he can post. Can you guys posting this do some vetting? Please?

    --
    -- Programming with boost is like building a house with lego. It's a cool but I wouldn't want to live in it
  115. "Comments make code more readable" - Myth? by Assmasher · · Score: 1

    I'm sorry, but that's not a myth. I'm sure, like all things, it depends upon time and place, but I assure you that the scanline hidden surface removal code I recently wrote that uses a span based methodology is entirely dependent upon good commenting so that debugging can involve someone other than myself. There aren't many software rendering specialists out there anymore. My code has excellent naming conventions, is organized clearly, but if you don't understand all the factors involved it would be laborious even for myself to debug this a year from now. Documenting the edge cases, the oddities, the factors other design decisions elsewhere in the system have made to impact choices in this code, it critically important.

    Hopefully it is commented thoroughly enough that someone reasonably proficient in Java and 3D could understand why things work they way they do. All of this is, of course, also included in a design overview document for this aspect of the system, but documents like that tend to get lost as time goes by. Documenting in the code why exactly we, for example, interpolate colors the way we do and then clamp them to an applicable range in critical to avoid someone messing up overbright lighting.

    Now, of course, this need doesn't apply in all scenarios. I don't heavily comment the model loader's methods (although they are well commented) to explain how we manage endian-ness and why, although I do mention to beware of this issue, but that's because in 3D this is a fairly common thing to have to support; ergo, I expect a developer with 3D experience to understand basic issues with modeling formats (if not the specifics of a particular format.)

    --
    Loading...
  116. interpreted? by Anonymous Coward · · Score: 0

    noone seems to have remembered the burden caused by over zealous commenting in interpreted languages as opposed to compiled where they comfortably vanish and save otherwise wasted clocktime.

  117. You want comments? Docs? Allow time for it. by bXTr · · Score: 1

    It always amazes me that management requires fully commented code and complete documentation, but they don't allow the time necessary to create it. You have to allow at least double the amount of time that you would give for coding because you are effectively writing the program twice. When time gets short, the first thing to go is the documentation. Your users don't give an unwashed rats ass about how well the code is commented. They care about whether or not it does what they want. Therefore, it's entirely up to management to allow for time in the project for documentation and commenting code.

    --
    It's a very dark ride.
  118. Myths about not commenting by buzzn · · Score: 1

    1) Comments have a cost ("When you update the code that the comment references, you usually have to update the comment as well")

    Worst case, sure. But the future maintenance cost of having no comments, or wrong comments, is higher than the cost of no comments. For example, if you code to an interface, and the interface does not specify what it does, then you have to go look at how it's implemented, which takes a lot more time. You might then say, well if the interface is wrongly documented... but then you're begging the question. Interfaces are contracts, and contracts require precise definitions.

    2) Comments make code less readable

    Wrong comments make code less readable, sure. But take a simple example:

    insertPositionalMarker(context);

    Why does this routine get called? What happens if I change it? Contrast with:

    // this fixes defect 12345, by ensuring list order validity:
    insertPositionalMarker(list);


    Woohoo, now I know why it's there, and if I later need to understand the context, I can easily back reference to the original bug, and if I feel the need to make changes, I can regress the defect.

    3) There is no need to document something that is obvious, and documenting same is a bad idea.

    Maybe, if you are a genius and know (or want to frequently review) every line of code. In the real world, however, we call other people's modules, and we use context sensitive editors that hint a range of possible calls, including overloads. Which one do you pick and why? Does the call have side effects? A concise description of the interface contract is imperative for productivity. Not having documentation requires asking them, or wading through their code. Either one is a waste of time.

    The fourth one in the article, code must always be self documenting, is correct, but trivial. Some code constructs are not obvious or readable, because they are complicated -- e.g. written by a domain expert.

    The original article is fine for simplistic code bases, but doesn't work in the real world of high productivity, large scale applications. Anyone who doesn't comment their code is trading a small amount of their time for a large amount of everyone else's, and that's not scalable or efficient. In fact, it's just rude.

    --
    Join the window installer's union, where prosperity is a brick throw away!
  119. Verbose variables by 4D6963 · · Score: 1

    Slightly off-topic : what annoys me most is being asked to use very verbose variable names (think 20+ characters), because it supposedly makes it more readable. That's utter bullshit, and the people who ask me this never did anything very complicated. It's much harder to juggle with a bunch of long variables than to juggle with two-letter variables. I prefer to use short variable names and comment them in a block at the beginning of the function.

    That's the very reason why mathematicians use one-letter 'variable' names. Think about it.

    --
    You just got troll'd!
    1. Re:Verbose variables by slaingod · · Score: 1

      Code completion is your friend. You should only need to type two or three letters to get to most of your long named variables anyway. And using long variable names absolutely makes thing more readable, especially in a local sense.

      When your debugger or log spits out:

      "variable 'hn' was undefined" versus "'host_name' was undefined", you might actually be able to fix it without opening up code, because it was just a configuration error.

      But even more generally, not having to grok to the beginning of a method or fully understand a class's internals to know what 3 lines of code are doing, helps the mere mortals out there like me, especially when traverse object inheritance several layers deep.

      And mathematicians do a lot of writing on paper where it actually does make more sense to use abbreviated variables, at lease more so than in modern computer engineering.

      --
      http://blog.slaingod.com
  120. Second Class Citizens: Code Comments by Anonymous Coward · · Score: 0

    I think that code should contain no comments at all.

    Notice that I did not say that code should not be commented.

    The problem here is that we are trying to do two things together, where we should be doing them separately. I'm envisioning a development environment that gives you control over your comments - you don't put them in the code - they live separately and are anchored to the code. They could be viewed separately (or together with the code), expanded and collapsed, and nested for varying levels of explanation.

    Comments today are second class citizens, but we should be thinking about providing a full set of features around the commenting of our code,

  121. Re:Not commenting is a sign of not thinking or car by Anonymous Coward · · Score: 0

    Bravo! Surprising that you have achieved so much insight in your short career of two or three high school projects, congratulations!

  122. Under and Over commenting by CrazyFool · · Score: 1

    Uncommented code is very often shitty code - and so is over-commented code.

    Uncommented code is good if you 1) will be the only person to ever, ever, ever touch the code, 2) you have perfect memory, and 3) you don't expect anyone else on the planet to ever use it.

    General rule - assume the person following you is *not* a uber-coding-adept but just some average-joe/jane code-mechanic who has far, far more work on their plate then they can handle already. And this isn't a freaking competition - you **are** allowed to give them a hand in understanding your latest convoluted masterpiece. You usually are on the same team.

    At my workplace they have a library of perl code. Most of it is pretty good _code_ and do usefull function. But there is very, very, little comments and the writers simply LOVED to use the latest arcane features of Perl. No subs are documented - "Hey - read the code!".

    Sorry but why should I have to read and try to comprehend your convoluted code just to use it? Its *your* responsibility as the author to make sure it does its job and its also *your* responsibility to document (and maintain that documentation) the interface to your code if you expect anyone else to use it. Its *my* responsiblity to follow your documentation and use your code properly.

    Also subroutine/module/method comments are often picked up by IDEs to provide on-the-fly documentation (or 'hover-help') for anyone using your code - I'll admit that I find this very useful.

    On the Other Hand - there are those who grossly over-comment their code. We have a bunch of these types of people as well.

    They Comment every single change and bracket their changes with comments showing the Change Request number as in :

    // FR: 1203938+

    ... Block of new code...

    // FR: 1203938-

    The results, over time, a patch work of these comments - overlapping each other.... The code ends up virtually unreadable. There are far more lines of these types of comments than lines of code.

  123. All I have to say to you is: by fishexe · · Score: 1

    totalEnergyResidingInAnObjectInJoules = massOfObjectInKilograms*speedOfLightInVacuumInMetersPerSecond^2

    oh, and by the way:
    gravitationalForceBetweenTwoMassesinNewtons = massOfFirstObjectInKilograms * massOfSecondObjectinKilograms * 6.673e-11 / (distanceBetweenCentersOfTwoObjects ^ 2)

    That should put you in your place.

    --
    "I don't care about the Constitution!" --Bill O'Reilly, November 17, 2009
  124. Think of the guy reading it. by Dark$ide · · Score: 1
    The whole nature of the comments in code is to explain why the result that the code creates or the function returns isn't as simple as you'd expect when you first look at the code. If there's nothing strange in the code, don't bother with the comment. If the code uses some funky technique explain in a concise way why you've written it that way and not used a possibly more obvious method.

    Too many folks create "write only" code that isn't worth debugging when it goes wrong and the better way to cure the bug is a rewrite. In those cases the comments are essential to avoid the need for the next guy maintaining the code to have to re-analyse the problem and rewrite.

    It gets worse when you add complexity. One thing guaranteed to make code unreadable is when folks create SQL statements with hundreds of predicates and tens of joined tables.

    1st simple rule is trust the code not the comments.

    2nd simple rule is don't comment the obvious.

    --

    Sigs. We don't need no steenking sigs.

  125. Re:Shorter sentences by CAIMLAS · · Score: 1

    Yeah, I re-read it after writing it and hitting submit. It's horrible. My apologies!

    --
    ~/ssh slashdot.org ssh: connect to host slashdot.org port 22: too many beers
  126. In reality, comments are secondary... by Turzyx · · Score: 1

    ... to the primary objective of getting the program working. Okay, okay, perhaps not... However, trying to construct coherent descriptions and code analysis during a 2am coffee-fuelled session usually results in the babble people complain about. I don't think I've ever opened up source code to see everything perfectly explained, and to be honest, it doesn't need to be.

    To me, the most useful comments are usually the ones that give a brief explanation of the objective (of that section of code). Any developer worth his salt can figure out what has been hacked together to achieve said objective. Having text blocks littering the page is just useless unless the original developer was a world class author.

  127. Raw nerve by Anonymous Coward · · Score: 0

    In a southern software company, the original developer (oh yes he was original) decided that it would be a good idea to delete all the comments from the code because he thought you should get inside his code and really understand it and not rely on unhelpful and potentially misleading hints such as comments. I rather suspect that he did it because he was threatened by the chimps they hired as the monstrosity he had spawned began to require more and bodies to maintain - a half a day for the most basic label change which usually went totally wrong. The code was mostly crap with occasional really shitty bits. Certain routines meant to run overnight took several hours. I glimpsed inside this man's head from time to time and was afraid. I'm still baffled how such garbage could have come so far (the company is let's just say not unsuccessful).

    All I have to say unless you are absolutely positively sure that you are god's gift to programming and what you consider wonderfully elegant code is universally intelligible - DON'T BE A FUCKING DICK AND COMMENT YOUR WORK.

     

  128. Re:Cliche, but false... by Anonymous Coward · · Score: 0

    Suppose you find

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

    What does the next developer see in the output of the documentation tool of your choice, and what does the compiler/interpreter see and use?

    A doc tool, if any, should damn well parse the relevant parts of the source.

  129. #2 is just wrong by Anonymous Coward · · Score: 0

    He misses the point. But actually states the point in his objection. Ie That he ignores the comments unless he's stumped. Duhhh... What do you think comments are for? They exist to identify the more non-obvious portions of code. Anybody can see that x = y assigns y to x. This isn't what comments are for. As stated in his #3.

    Comments are useful when used correctly. The problem is they usually aren't used correctly. How many times have come back a year later, read a comment, and wondered what the hell you meant by that?

  130. Good commenting... another art form by hazydave · · Score: 1

    Just like programming, the proper use of comments is an art form. Yes, there are plenty of really stupid comments in code... you don't need line-by-line comments describing the obvious behavior of the code. Well, unless you're writing in APL or some other "write-only" language.. no no-trivial line of APL code is obvious. But proper comments should describe functions, large blocks, and classes... not just what they do or how they work, but what you're thinking and why you did things that might be non-obvious, even when the code looks clear and well written.

    There can also be commenting formalisms. I have worked at several companies that used some form of "auto-docs"... basically, when you commented a function, you wrote the documentation for folks calling that function from other modules. I put this feature into the interface description language I wrote as part of an object model for an object-based OS. There were both "formal" and "informal" comments. Informal would be used for very specific little details, formal became part of the hypertext (OS/2 or HTML) generated during every build.

    And yeah, in any autodoc-type situation, comment maintenance is part of the job, no less important in the long run than the code itself. In fact, potentially much more important... a bug in your code breaks the system at one point. A bug in your autodoc comments can break the code at any number of points.

    This same project also had a mess of pretty cool things. Some weren't useful outside of our object model... the compiler generated a database of pre-compiled object tokens. The release system formally enforced the use of the official release version of the compiler from the server, for a formal release (you could use any compiler you wanted to for testing). This release system also sent release packages out to various other sites in our company, automatically installed, compiled, and merged databases during the "catch" process, etc. You could always build identical code on any PC (OS/2 or Windows NT), with no worries about missing libraries, etc. Not much of it was applicable to code development outside of our specific custom OS, but in the end, it was a very cool system.

    --
    -Dave Haynie
  131. Re:How does this even deserve a /. ? by hazydave · · Score: 1

    Agreed.

    When I first learned to write code, it was 1973 and I was 12 years old. Not commenting things worked ok for a few years, when I wrote trivial programs, rarely went back to them, and had a nearly perfect and fairly uncluttered memory.

    It wasn't a whole lot different in college. I did learn to write decent comments -- you were sometimes graded on this ability. But again, one project per week in some classes, all your own code, never to be revisited. Comments went one-way... and I'll bet there are coders here who are still at that level.

    I got the first hint in my CAD class, which I guess was a Junior or Senior level project engineering course at CMU. In this class, the whole class was engaged in developing the core of a single CAD program. You got everyone else's modules and had to integrate them into the shell of your final project. That was one example of where comments became pretty important.

    Here's another one... I started a program sometime in 1986. I wound up working on it, off an on, for the next 12-something years. It became critical to keep things well documented. This was "DiskSalv" for the Amiga computer.

    There are other cases.. sometimes, it's that clever hack that took you a long time to figure out. Another Amiga thing was a trick you might find rare these days... you wanted to reset the system without losing your program's control. The problem was simple.. when you hit reset, you normally got a usual 68000 reset vector, but not the one you wanted, necessarily... since upon reset, a ROM magically appeared at the reset vector, and RAM vanished. So I came up with a hack that organized things just so, so I could count on the prefetch buffer allowing me to turn the ROM off and then jump where I wanted. So it was a few lines of code, and all kinds of commenting to explain why this was (far as I know, ever) the only way to do this on any Amiga computer.

    Later on, as mentioned in another comment, I worked in places that made comments part of the forrmal documentation... using simple (and not so simple) tools to extract comments from the code, create hypertext links, etc. (on Amiga and later at Scala, Inc.) The ideal place for the documentation on the code is, absolutely, in the code.

    --
    -Dave Haynie
  132. Commenting units by SplashMyBandit · · Score: 1

    One thing I notice (as a former physicist turned developer) is that computer science trained folk are very poor at documenting their *units*. For example, a time duration may be in days, years, milliseconds. Without either naming your variables with a unit name (eg. sleepDurationMillis) or putting in a comment stating the unit of measure at the point of declaration it becomes infuriating and risk-prone using other people's code. Comments are absolutely essential to document the units that variables use. It's also useful having light commentary describing the preconditions of a method and what will cause it to fail - that's one way to get more robust systems - yet few people do it. I only learnt these things after decades of maintaining and extending a lot of other people's code. Therefore I consider the "don't comment" brigade to be rather n00b in their outlook, despite thinking they're l33t.