back to article Sweet, sweet smell of comments in code?

Arguments rage over the importance of adding comments to your code versus the importance of writing clear code that speaks for itself, thereby potentially eliminating the need for comments. The dichotomy boils down to this: writing comments versus writing self-commenting code, as if comments and clear code are somehow mutually …

COMMENTS

This topic is closed for new posts.
  1. sheepdog
    Gates Horns

    Shotguns too messy

    "Months later, someone will look at your unclear or uncommented code, they will go out, buy a shotgun and hunt you down."

    Personally, the BOFH cattle prod is far more cleaner and quicker solution for me.

  2. James Anderson
    Happy

    Im for minimal comments

    Having had lots of experience looking at other peoples code

    I learned to ignore the comments and look at the code first.

    The code might not be clear but its always right, whereas comments can be downright lies.

    I try to restrict comments to:--

    - explanations of how to use an API, public method etc.

    - an explanation of non obvious requirements

    e.g * empty tankers not allowed through Mersey tunnel

    * but full ones are OK!

    - expanations of non obvious external API calls

    e.g. /* tcpipkeepalive not a promise of eternal life

    -- really means "tell me when connection is dead" */

    Otherwise I beleive the old Mantra "if your code needs comments it needs rewriting ".

  3. Maty
    Pirate

    comment

    Never comment your code. If it was hard to write it should be hard to read. Besides, what are the advantages - to you - of anyone else knowing how you coded a program?

  4. amanfromMars Silver badge
    Alien

    Plain TeXXXXTCode

    "Sometimes comments are copied and pasted along with copied and pasted code. That means the code is then changed but the comments aren't, resulting in comments that essentially tell lies about the code."

    Yes, Matt, Guaranteed Original Trusted BetaTesting Source is Most Precious and not available from just any Ole Candy Store/Curiosity Shop. :-).

    With Total Information Awareness Command and Control are Comments in Code unnecessary?

    Critical InfraStructure Planning with Virtual Defense Forces is surely Best Beta done in Full Sight on the Web of Networks InterNetworking. Media can then do what it does Best in Beta and Create the Show.

    Currently their Quantum Awareness is being BetaTested and Tempted. Jumping into Action isn't their Usual Forte...... and Quantum Leaping into CyberIntelAIgent HyperRadioProActivity for Virtual Control is AIdDecided Leap in Belief in Oneself too.

    Now some may posit that that sounds demented, whereas it is anything but. It is merely wiser Imagination finding a Server 42 Send 42 Server........ which all came about after thinking that Terry Pratchett's Vivid Imagination could Present an Alzeimers MisDiagnosis.

    Maybe Terry is just Virtually Psychotic and HyperManic, which is Perfectly Normal as one Matures and Grows. An Evolution in Thinking rather than any Illness.

  5. Mark

    A Homily

    One I use in cases like this (in fact with all "coding practces":

    Rules arefor the guidance of wise men and the obedience by of fools.

    Think about how do you comment when you'd use a particular object or element? If code commented the code then you'd not need a man page.

    Code should be clear in what it does and comments should put down anything that needs to be said but cannot be coded.

    Putting the code in another smaller class with an evident purpose is a common thing with people who don't debug their code. When to find out what class X does you have to dig back to class A via W, V, ...

    I comment code until *I'm* happy with it and ask someone else to read it and see if they can understand the code/comments.

    Seems to work.

  6. Mark Honman

    Comments - best on top

    I wholeheartedly agree that comments mixed in with code are the stench of death (unless it is assembly code!!!).

    If you need a comment to explain what a particular line of code is doing, it's very bad news for anyone who will be maintaining that code.

    And in the days of 24-line terminals having comments interspersed with the code made it hard to get a routine onto one or two screens' worth of space.

    *However* it is incredibly useful to have program heading comments, which can be laid out as follows:

    2-4 line description of the routine's purpose in life.

    description of the parameters - what they mean

    any side-effects

    if the routine is a bit hairy, a structured english (remember that) description of the routine's logic.

    It works really well to write all of this *before* beginning any coding - you have thought so much about what you want to do that the resulting code is high quality stuff. Not to mention that if you struggle to write the comments, the routine as designed is probably too complex & should be refactored *before* you start any coding.

    The modern idea of writing the tests before the code has a similar effect in making one think about the code you are about to write - but doesn't result in documentation of the "why" in the same way.

    All in all, concise heading comments save more time than they cost... as long as one doesn't get too religious about them.

  7. Anonymous Coward
    Anonymous Coward

    Languagehasgrammarandsyntax

    andpunctuationcompoundwordsdonotsocontinueusingcomments.

  8. Pete Silver badge

    this argument was old and boring 20 years ago.

    Code without comments is like a cartoon without speech-bubbles. You can work out what's going on, but you lose a great deal of detail - and it takes a lot longer, too.

    No matter how you package it, there is no excuse for writing code without providing a commentary about what it does, why it does it, the assumptions the author makes, why a particular technique or construct was used.

    Somewhere, you need to provide information about the state of each module (test, production, change-history etc.). This can either be in the code itself, or in a management system - either way, it still counts as comments and is part of the code-base.

    This debate about commenting code crops up with each new generation of programmers - who don't have the experience to realise why, or the discipline to actually write clear, well constructed descriptions of their code. Luckily it's a good way to differentiate the hackers from the professionals: just look at the quality of their documentation.

  9. Anonymous Coward
    Anonymous Coward

    Comment on comments

    I also consider comments to be a courtesy to other developers, to save them time. Comments are helpful, as long as they are not overused/misused.

    Anyway, never mind comments; I spend a lot of time reformatting code to just make it legible. Tabs should be banned and poorly-named variables are the bane of my life.

    I'm sure some of these people deliberately make their code impenetrable, lest others realise they are not indispensable and replace them. The irony of that, is that at my company, those who don't follow the company standards are the first to be chucked out.

  10. Anonymous Coward
    Thumb Up

    Javadocs are not really comments

    I think that javadocs do not count as full comments. There are a lot of tools that can check javadocs and ensure that they are somewhat useful. (e.g. checkstyle)

    These tools can be used to fail a build if javadocs do not contain required content.

    One common fault of javadocs is that they are all just "todo", "write me...", or "Created by IntelliJ IDEA". A simple checkstyle rule soon puts a stop to that, and you get one sentence descriptions that are no worse than the method name in terms of accuracy!

    (Oh an let developers autogenerate javadocs for the getters and setters)

  11. Paul McConkey
    Flame

    Of course you need comments - only an imbecile would disagree

    It's all very well using a high level language in a way that allows for the code to self-comment, but try doing that with assembler. Of course you have to comment your code in detail, otherwise how the hell are you ever going to remember why you did it the way you did it? Junior programmers working on simple projects in C# or Java can maybe get away without comments, but old pros can't.

    And while we're on the subject, forget about commenting for others - the comments are there for you (especially as the grey hair goes count goes up and the grey cell count goes down).

    And what about the comments that refer you back to the original specification or even international standard/RFC so that you you can remember why you wrote the code in the first place?

  12. James Battersby
    Thumb Up

    Help for all

    Comments are always a good thing, particularly ones that follow a structured syntax such as Javadoc. I admit there is no need to comment EVERYTHING such as:

    //increment x by 1

    but if the code starts going into complex recursion or is the interpretation of a complex equation then codes should provide all the help they can give.

    I wrote a statistical equation a while back and it wasn't until much later that a statistician could highlight the incorrect part when it produced erroneous results. This statistician doesn't understand any programming language (save SAS) but because I had commented in the right areas he was quick to point out the flaw.

    I'm quick to admit that I am not the world's most competent programmer so I rely heavily on comments to inform me what each and every method does. I get incredibly frustrated when I can't pick the most appropriate method for the situation simply because the author was too lazy to write a few extra lines.

  13. Steve
    Go

    and back in the real world

    Most developers try to write clear code and sprinkle helpful comments about where necessary.

    Moving your code to find the white rabbit into it's own method doesn't make it any clearer why a white rabbit indicates the start of the month, a comment explaining why should be part of the javadoc for the method.

    It's rare (so rare I've never even heard of it) to have to ask someone to comment less, so

    x++; //increments x

    is about as likely as, well, a very unlikely thing.

    In conclusion, write clear code, and add clear comments to it, the two are not exclusive.

  14. David Higgins

    comments essential for non-experts

    As a beginner in a number of languages, it is very, very helpful to have even the simplest lines commented. Same goes if I want any other beginners to understand what I've written.

  15. Henry Cobb
    Thumb Down

    Define the contract, skip the fine print

    Comments should not be placed inside blocks of code.

    If the code is so complex as to be non-obvious then break it up into finer methods/functions/modules until each piece is obvious.

    As you write each chunk, prefix that method with the contract of what it requires and what it promises to do.

    If your compiler cannot inline, unroll and omit then get a different one.

    Switching programming language, toolset and OS platform is a LOT less expensive than producing code that cannot be maintained.

  16. Anonymous Coward
    Anonymous Coward

    <no title>

    Always comment one's own code since it saves having to have the service documentation open at the same time. Not all languages allow for clarity in code alone, if any do. "x = 1" is used because "FirstDayOfMonth = 1" may well not be an option. And anyway, one's own comments are always 100% correct.

    Treat someone else's comments with caution. It may explain what they were attempting, if they kept their comments up to date; but yes, scan the code to see what it seems to be doing first. But reading other people's code, when they couldn't be arsed to comment, can be a nightmare, multiplying the time taken to understand it by many factors. Especially irksome if the original writer comes up with a load of excuses why they didn't comment.

    Don't delete someone else's comments uness a) you have taken over responsibility and they won't be looking at it any more, or b) it is clear the comments are wrong.

    Write code as clearly as possible. Comment it extensively to be clear. Those that don't want to read the comments need not; most modern text editors will allow the comments to be in a different colour to the code, so easily ignored.

  17. jon battle

    Comments about comments

    - Hmm I guess the theory is clear enough: if the code were self-explanatory, you wouldn't need to explain it with comments.

    - But in practice, when I read zillions of lines of code, I find the guys who do zero-comments are precisely the same guys who write incomprehensible code that begs for comments.

  18. Anonymous Coward
    Alert

    Facile comments

    Seems to me in reading the comments on this article that I can spot the real programmers.

    By "real" I mean those who have coded in the real world for a considerable time, not those who lark about in a CS lab or at home.

    In the real world we see these fads come and go and couldn't care less. Code style and commenting or not is a function of experience and project complexity. Saying that code is bad if it includes comments is typical of someone who writes small scale applications in a high level language like Java or VB. It would be interesting to see their attitude when getting to grips with multi-million line projects involving many interacting modules.

    Personally, most of my own work is quite low-level involving device drivers and interface modules. Even with clearly written C code, I doubt many of the so called uber-programmers could pick up a lot of the intricacies of locking, synchronisation and resource management without some significant comments to help them.

    No doubt these people wouldn't consider me worthy to join their 3lite club. On the other hand, I wouldn't give them a job and nor would most Dev managers.

  19. Anonymous Coward
    Coat

    Remember Pseudo-code?

    I work with a team of developers and one of my main responsibilities is to make sure no one is stuck and they are moving forward towards a solution. They are not expected to be domain experts. That's the job of me and the customer. One of the best ways I found in my 30+ years in the business is to communicate the business rules could be something like (trivial example warning):

    //when a service request is received

    //get the user account balance

    //if they are in credit

    //service the request

    //otherwise

    //send them a bill

    //set an action for if a payment arrives

    //set an escalation if no payment

    //in any case clean up after yourself

    They can fill in the blanks. And if they can't they come back for refinement.

    It's lightweight, lends itself to small unit tests and gets the job done.

    I always encourage them to leave the comments in because it might be me doing the code review and if I've slept between writing it and reading it I'll have forgotten what it was about.

    Tweed with leather elbow patches...

  20. Mark
    Dead Vulture

    "Tabs should be banned"

    F'n A!

    Tab stops were positions on the page/typewriter travel that you dinged to with a tab stop. It allowed indentation of a block of text or list points.

    With computers (is this the fault of Word and other WP wannabe's?) the tab was "move some distance along" which is completely different.

    Wordprocessors should not have used Tabs except where it meant "move to the Nth tab stop, tab stops being defined <here>". And programmer tools should NEVER have used them except to mean "indent this line appropriately" and changed that to the number of spaces needed to do so.

    Worst example of handling tabs is where you have auto indenting and every X spaces indented is replaced by a single tab and if there were spaces left over, these were represented by spaces. AAAAAGGHHHHHH!!!!!

    (that's me, that bird...)

  21. Jon Green

    Some simple reasons for comments

    The most important point about a (well-placed) comment is that it illustrates what was in the programmer's mind.

    If you're reading a code comment, it's because you are revisiting code and need to understand what the code does - and that's usually for one of two reasons. Either (1) you need to debug it, or (2) you need to modify it.

    In debugging, an expert uses the comments to understand the coder's thought processes, and trace back to where they went wrong. Without comments, the reader is forced to follow the mechanism of the code, not its intent, and that can lead to falling for the same fallacies as the original developer did.

    Likewise, when modifying existing code, sometimes comments are the only thing that saves you from repeating the errors of the past. I'm delighted when I see something like:

    // The datasheet says set bit 10 here, but there's a hardware

    // bug. If you do that, you'll gate VCC and GND onto the same

    // output! Instead, set bit 3, which does the same job, safely.

    Bare, uncommented code could not convey this vital information. It's unreasonable to expect a developer (or maintenance programmer) to memorise every piece of out-of-line documentation and keep it all in mind at every line of code, so documenting assumptions and discoveries really does save time and effort (not to mention stress) when revisiting code.

    Code should self-document, as a general rule - but *good* comments can make all the difference when it's time to look again.

  22. Anonymous Coward
    Flame

    Screw you guys...

    I spend most of my time looking after my own code and I've learnt the hard way that my comments are there to save /me/ working extra hours when I'm on a customers site and want to get home. Just because it seems obvious when I'm writing it that doesn't mean it's obvious (even to me) several months or years down the line. Go ahead and leave your code uncommented but don't expect people to care when you're the one who's having to work extra hours on your own time to fix it.

  23. Anonymous Coward
    Flame

    Same old arguments

    If coders learnt to think clearly and identify what is important rather than worry about some arcane abstract extreme argument that has been going on for years then maybe we'd have less problems with software

    But sadly far too many have no ability to be pragmatic so we end up with lots of stupid debates about triviality while you can drive buses through the bits the automated tests miss/comments don't tell you

  24. Paul Naylor

    I have to comment...

    ... it satisfies the ISO9000 woman whose eyes glaze over when I tell her that I'm not printing out every single script I publish for a project job bag.

    Interestingly though, I was in a training course a couple of years ago by a qualified Adobe Flash trainer who said that I should pretty much comment everything. And if I change a lump of code, I comment it out, along with reasons why it's been deleted. I thought that was going a bit too far.

    Personally, I use a lot of comments, particularly at the beginning of a function (or method) because I use a lot of array structures and my memory is so bad I can't remember my own code a couple of months later...

  25. Antony Riley
    Thumb Down

    Bla

    I wish people would stop trying to think up new ways to write code, few if any are actually any use in practice.

    Q) What makes good code ?

    A) Good programmers.

    Personally comments are useful during the design phase of a project, and it's perfectly sane to clarify your ideas by writing abstract code with good comments, of course when your design changes during implementation (it will) you must remember to update the comments in your abstract code.

    All these guidelines to programming take one or two aspects of programming to the extreme, but they are presented as absolute guidelines. Sometimes pair programming is useful, sometimes comments are useful, sometimes test cases are useful, sometimes refactoring techniques are useful.

    All these things are part of a programmers toolkit, the difference between a good programmer and a bad programmer is knowing when and where to use the different tools, taking a few of these to the extreme neither makes you a good programmer nor produces good code in a timely manner.

  26. BoldMan

    @Mark

    Take a chill pill!

    Real world developers use comments as much for our own benefit as for others coming after (poor bastards).

    CS graduates (spit) and Java obsessives can go do whatever the hell they like, so long as they don't join my team.

  27. Anonymous Coward
    Paris Hilton

    Comments on Errors

    I did read some comments in a program which stated that the following code was created to duplicate an error the user reported, and then the code was commented out to stop the error repeating itself.

    But the best was the comment

    //This code is to correct an incorrect correction made incorrectly in January.

    Paris, because there is never a picture without a comment about why the picture was taken. So a picture is not worth a 1,000 words.

  28. Paul McConkey
    Flame

    // Arghh!!

    Never comment out code - delete it. If you are afraid to delete code you shouldn't be writing it. What on earth is source control for except to keep old versions? Don't keep junk in the source it's worse than anything.

    Apart from crude/offensive/juvenile comments of course.

  29. Anonymous Coward
    Flame

    "Tabs should be banned"

    Er, why? the point of using tabs is to allow other programmers to view your code with the degree of indenting THEY prefer, not the number of spaces YOU prefer. I agree that tabs and spaces should not be mixed - "Spaces should be banned"!

  30. Anonymous Coward
    Stop

    Try using non-trivial examples

    The no-commenters always demonstrate their point using simple ten line extracts. Possibly this is for the sake of brevity but comments only really come into their own on real, lengthy programs not ten line snippets. Sure you can do a lot with meaningful identifier names, and breaking up code into logical sections help, but there are always subtle points that need to be explicitly documented.

    Examples that come to mind are simple counters - are they 0 or 1 based? Variables that hold an aggregate value of a data structure (eg length) are another case - do they get updated before or after the corresponding structure? Things like this are easy to resolve in a ten line program, but not so when the variable is referenced in half a dozen places hundreds of lines apart.

  31. Steve

    Re: rather than worry about some arcane abstract extreme argument

    You miss the point. If it wasn't comments vs. no-comments-needed it would be functional vs. imperitive, garbage collected vs. not, pure OO vs. C++, Java vs. C#, Scheme vs. Common Lisp, Pascal vs. C, Fortran vs. Algol, Cobol vs. sanity, 3GL vs. assembler, or if all else fails there's always XBox vs. Playstation, Atari vs. Amiga and Commodore vs. Spectrum.

    As programmers, we need some way to vent the frustration. Any convenient two-sided religious war will do.

  32. Robert Woodhead
    Happy

    Comments are Literary Expression

    I've been programming so long that I don't write code anymore, I just remember it and type it in again... So from that perspective:

    Comments serve several purposes:

    1) To explain what the code does.

    2) Ummm.... no, to explain what you EXPECT the code ought to do, in a perfect world.

    3) To remind you (and others) about what you were thinking about when you wrote the code.

    4) To brag (even if just to yourself) about a particularly nifty bit of code, and to pass on that slelegant (sleazy & elegant) hack unto the next generation.

    5) To explain (or make excuses for) why you perpetrated some abomination or another. There was a good reason, honest!

    6) To provide clues to the poor bastard who will take your place after your fatal encounter with the BOFH.

    With respect to the last of these items, one should always take a little extra time to make one's comments literate and entertaining. The poor bastard who comes after you (heck, it may be you 5 years down the line) will be suffering enough, anything you can do to reduce the pain will be appreciated. At the very least, it will reduce the number of times someone visits your grave to piss on it.

    Those who claim that good code does not need commenting should be sentenced to have to rewrite some of their own 15-year old code in a different language and operating system... oh wait, that's silly... they haven't been programming long enough for that!

  33. Steve Kellett

    Au contraire. Shotguns are too quick & painless

    Having spent the first half of my career tracking down and fixing bugs in the guts of a DBMS that had been incrementally developed since the early 70's[1], my reaction to uncommented code is about the same as my reaction to the idea that a hierarchic object model is sufficient documentaion of an API[2]: The desire to hunt down the perpertator and put them out of my misery using only a blunt pencil and a set of kiddy-safe scissors :D

    I can read the code. I can see what it's doing, but I need to know what it was trying to achieve so that I can work out how to fix the obscure bug that's been hiding in it for ten years and has only just come to light...

    1) Including a couple of source code conversions for good measure.

    2) Rather than clear examples of how to use the parameter options.

  34. Simon Neill

    I love my comments

    I put comments all over my code! not obvious things like "//set x to 1"

    more like:

    // main loop

    // open files

    // display output

    to separate blocks of code, then if I need to find where in my code each bit is I can just hit ctrl F.

    Another handy trick is to comment closing braces, really helps keep them paired especially when you have nested ifs in nested loops and need to move them.

    Not to mention that scribbling some pseudo code comments when you have a brainwave on how to write the next method can really help.

    The idea that code shouldn't be commented is ludicrous. To me, comments are like post-it notes. Great to have when you need them, but covering your code with them is a sign of problems.

  35. Ian Michael Gumby Silver badge
    Flame

    Poor example.

    Pretty piss poor example concerning documentation.

    Can code be self documenting? Maybe.

    You add comments to your code for a couple of reasons...

    1) You write a lot of code and when you go back 6 months later to modify or add additional functionality, you don't remember writing the section of code.

    2) Someone else who may not be as familiar with your code will be forced to maintain it.

    3) Your code is going to be supported by some sod in India or someo back water cheap labor pool and they don't know how to program well enough to understand what you did.

    4) Coding is a team sport these days and the rookies coming out of school don't know jack.

    So while choosing the names of your variables to make sense, you still need to comment the code too.

  36. Anonymous Coward
    Boffin

    Tab WTF

    "Tab stops were positions on the page/typewriter travel that you dinged to with a tab stop."

    "With computers [...] the tab was "move some distance along" which is completely different."

    Er .. WTF?

    With Word, the tab means "move to the next tab stop". These are the little "tab stop" icons at the top of the page.

    With a text-editor, the tab means "move to the next tab stop". These are the positions which are zero mod N where N is the "tab width".

  37. Andy
    Stop

    Sigh

    As usual, Matt Stephens sets up a straw man to knock down...

    Comments are not a smell.. In fact, in the description of code smells (from the book 'Refactoring'), comments are listed as a deodorant, something that can be used to mask bad smells.

    The idea is, if something needs commenting, it's because it's hard to understand. If you can make the subject of your comment easier to understand, then you don't need the comment.

    This removes the issue of having to keep the comment and the code in sync (especially important if the comment lives at the start of a long method and you can't see it at the location where you are changing the code)

    If you are working around an API, then you can't do anything to improve the code, so comments are useful.

    A comment should represent a useful and hard-earned piece of information that will save you (or your colleagues) time and heartache at a later date.

    Matt's example with the rabbits and the first of the month is a poor example. If finding the rabbit is the important step, then the method *would* be called findRabbit, it may be called by a method isFirstOfMonth (if we find the first of the month by finding white rabbits)

  38. Anonymous Coward
    Anonymous Coward

    Re: Facile comments

    I have to agree absolutely with Anonymous Coward (re: Facile comments) and John Green. Comments document the purpose of code, not how it works. My day job is programming a very large, 12-year old C/C++ Win32 API application, that was written in a real world environment (read: real competition, budgets, 3rd party integration with forced deadlines etc). Anyone out there that thinks a 12-year old bit of code is going to be relentlessly re-factored in it's life time to ensure that it's always self-documenting is out of their mind, or at least out of business.

  39. Graham
    Alert

    I smell the unhealthy stench of a crusade.

    I'm sure there are some occasions when comments aren't needed... and I'm sure there are occasions when comments aren't helpful.

    And I'm sure that trying to write better code is a laudable aim.

    But.

    In the world of Enterprise Software, where multiple groups of consultants and teams of contractors come and go, comments are essential.

    Why? Well it comes down to the premise that "if you need comments then your code isn't good enough". Not sure I agree with that but let's keep with it for a moment. If you've had 5 different groups of consultants or contractors working on some code are you going to be the one that stands up in front of the board of directors and says "I'm sorry but we're screwed. We told all our consultants and contractors that they should rewrite their code until they didn't need comments and because they all have their own writing style it's now a convoluted pile of cack that no one can understand"?

    Thought not.

    Comments aid communication; over use of comments doesn't but overuse of code doesn't either. The goal of good code and good comments to be able to understand the functional target of the code. If it needs comments put it in, if it might possibly need comments in the future put them in.

    But don't ever leave commented out code in place; some muppet will invariably uncomment it and cause havoc (either Gonzo or Fozzie Bear, not sure which).

  40. amanfromMars Silver badge
    Alien

    Garbage In .... Garbage Out

    If Coding is so Important Nowadays, maybe all Programmers should be Vetted to ensure they are not Programming when Feeling the Lonesome Blues and Manic Depressions....... and Panic Attacks .... and Psychotic Episodes. Let's Keep IT, at least, In Sanity.

  41. Anonymous Coward
    Stop

    @"the point of using tabs...

    ...is to allow other programmers to view your code with the degree of indenting THEY prefer"

    Unfortunately, this isn't always possible with some editors, so the only reliable method is to use spaces. I've never had a problem with other people's indents, just the editors' poor interpretation of them.

    Anyway, I indent to the level my employer has specified in their standards.

  42. George Johnson
    Unhappy

    @Simon Neil

    I thought I was the only weirdo that commented at the end of braced blocks of code, so I know where my exit points are! Especially useful on black and white terminals and there are no block highlighting tools to hand.

  43. Anonymous Coward
    Coat

    /* You are not expected to understand this */

    In an I'll-get-my-coat moment, I'm reminded of the most famous comment of all, from an early UNIX source.

    /* You are not expected to understand this */

    http://www.cs.bell-labs.com/who/dmr/odd.html

    Personally I comment my code with meaningful explanations where necessary because in the past I have been the shotgun-wielding coder taking on someone else's impenetrable code and I don't want to wish that on those who follow me.

  44. Mark

    Mixing tabs and spaces

    Is what winds me up about using tabs.

    And "indent 2 spaces" or "indent 4 spaces" is irrelevant: indent CONSISTENTLY. Heck, I've heard good arguments for 3 spaces (exactly): if you cut'n'paste an even number, if you miss the column by one you can't tell which way you did it if it's even. If it's three spaces, it is obvious which way you were off.

    And often the "standard" breaks using tabs anyway. E.g. function calls that expand more than one line should be indented to the level of the opening bracket. That's unlikely to be a tab stop.

    If you are consistent in your formatting, any format changes needed can be done with a simple lint program.

  45. Hywel Thomas

    Comment Fan

    I'm pleased to see that I'm not alone in commenting for my own sake. Over-commenting is better than under-commenting.

    I find that big blocks of comments above methods are MORE likely to go out of date than those inside, especially those that list things parameters or variables used. The method signature should give a good idea about what it does, but comments about what it might be used for can still be helpful.

    I think the key to comments in method bodies is to answer the Why? questions. The code says what it does, but not why. This is especially true of anything that's in there to work around a problem (possibly in 3rd party software or hardware).

    Ban tabs.

    Encourage white space. Blank lines aid readability.

    Oh yes. Put the open braces on a new lines (except for single statement blocks).

    Lastly : Give comments an extra level of indentation - it moves them out of the way and aids readability (less important with coloured code, but marvellous on a VT220). And if they're distracting from the code, stick a blank line beween the comment and the code.

    Commenting closing braces is an interesting one. Can be very misleading if they get out of step. I still use 'em though. Benefits outweigh the drawbacks. The real answer here is to ditch curly braces at the language level and to force code to be explicit (i.e. endif, endwhile, endloop, endcase, endswitch, end <methodname>, etc.

    And if we're going to tweak the language anyway, ditch the stupid ==, and use = as it was intended, picking something else to indicate assignment. I dunno, := or something ;)

  46. Hayden Clark Silver badge
    Unhappy

    // Add 1 to x

    Never seen this? Maybe you don't have code written by an ODC. They are told that "comments are good", and so they spew forth reams of nadadoc like this. Sigh.

    Plus this gem:

    unsigned int numVar;

    #define INIT_VALUE -1

    .

    .

    /* Proper casting to remove warning*/

    numvar = (unsinged int)INIT_VALUE;

    Well, the comment says it all, doesn't it?

  47. Graham Bartlett
    Flame

    @David Higgins

    If you're a non-expert, you have no place being let loose on the code on your own. Either you become an expert in your own time, or you get a mentor to keep an eye on everything you produce until you *are* an expert, and a coding standard ensures that you can't shoot yourself in the foot too badly. Even then, reviewing will occasionally catch odd corners of the language you didn't know about, but that's why we're all learning all the time.

    I don't know about you, but I'm working in a community of 500 experienced software engineers. It's significantly easier to train up a new graduate until they're safe to go out on their own, instead of dumbing down everything that we do for each other - and it produces better code.

  48. Anonymous Coward
    Dead Vulture

    Comments=Goodness

    I've supported other people's code, 5 years after it was written, and comments (even wrong ones) can save a lot of time figuring out WTF they thought they were doing.

    I've also been interrupted and come back to my own code a week or month later and the same still applied.

    As far as testable comments, use formal methods (Z, B, VDM, etc.) to specify what the code is supposed to do and to generate test cases from.

  49. Anonymous Coward
    Anonymous Coward

    My argument...

    ...is for myself.

    I do whatever the crap I want.

    I write superior code, but comment when and where I feel like.

    On a serious note. I think comments are good whilst in development when sections are not finished etc, it also makes positions easier to find when you are having to shift back and forth, and as placeholders where code needs to be finished but you need to work on something else first. Nice little "internal" todo list too.

    Obvious things like not putting large amounts of code into recursive code and calling out to procedures make coding much easier to read. Basic things like this helps the "what" the code does is easy to read, you just have to sort "why" it's doing it, which is not always easy to make self explanatory in code.

    Going out of your way to code something to make it "easier" to read, could actually just make the code more complicated than it is, whereas a comment affects nothing.

    Anyone that copies some code and makes changes without looking/changing the comments, well they are the ones to blame, not the comment writer. Why write maintainable code for someone that cannot maintain it?

    Car Analogy...

    Here is a car that you can fill up with oil yourself.

    Result: A car that never has its oil changed.

    I'm not suggesting that they shouldn't make it easy for us to change our own oil, but there are so so many people that don't even bother, and most the time don't even know how!

  50. John Tuffen
    Linux

    Comments again.

    Self-documenting code is a crock of cack.

    You try to debug some, to quote a friend of mine:

    ”… well, weenieboy, if I’m in there fixing the code, it’s probably because it doesn’t do what it’s supposed to..."

    And why is: "x++; // increment x" always trotted out as an argument against comments? I mean, really. The only peopl who write code like that are people learning a programming language. It's like banning a letter of the alphabet because it's used in some rude words and you may ultimately offend someone...

    Linux proponents seem the worst offenders for 'self documented code'

  51. Kurt Guntheroth

    comments are as useless as...

    Comments are not needed. They are as useless as spaces, punctuation, multi-letter variable names, type declarations, classes, and every other artifact of symbolic programming. Everybody knows that the real way to program is by simply providing each program's Godel number. Anything more is redundant, right?

    Comments tell you why. The code can't tell you that. Comments tell you what the statement means in the problem domain, even when the code does not. Comments give meaning to programs written in languages that do not perfectly capture the meaning of what you are doing.

    Comments remind you why you chose to do something clever rather than something simple. Comments remind you about things you had to learn in order to understand the code.

    Good programmers write comments. Programmers who don't write comments are either doing work too boring for good programmers, or they are too fresh to have learned the lessons taught by refactoring their own code.

    It makes me so tired to hear these rationalizations over and over through a long career.

  52. Daniel B.
    Boffin

    Comments...

    Back in my data structures college course, I found a quirky bug with Borland's Turbo C++ compiled code: when using the graphics routine, some of the dynamically-allocated memory would corrupt, bringing in interesting errors. So I made up a small code block that would verify the data before printing it out to the screen, and would correct it if there was a mistake. This was non-standard, so I commented it.

    One year later, I gave this code to other students taking the aforementioned course ... and while they didn't understand much of that block, they did know that code was not to be messed with, and *why* it was there.

    I could give many other examples ... like using the Active Directory "LDAP" from Java ... (just try to add a user AND set its password at the same time!)

  53. Maksim Rukov
    Heart

    I love comments too

    Yes, I love comments too. People have made lots of good explanations of why comments are are good so I won't repeat what's been said.

    Except to say that one of my favourite uses of comments is as a sort-of self-guide. Say I come to the point in the code where I need to do something semi-complex. First, I write a comment explaining it:

    // Does the widget fit into the widget box?

    Then I write the code. I find writing the code a little easier because I've got that plain-english description in mind.

    It's nice that it helps me as I'm writing it *and* it helps me or someone else reading it in the future.

  54. Anonymous Coward
    Coat

    gah

    It seems fairly clear here that the people who don't advocate commenting code are the people who either a) left uni in the past 5 years, or b) think they can write s/w because they've done some C# or Java. (Perhaps a) and b) are actually the same?)

    It's quite simple really, comments *must* be present as a high level description of what is going on - you can read the comments without reading the code. If you change it, then change the goddam comments. It'll save your ass one day. Just think about all the times you've had to implement a quick fix, on a live system (oh no, can't do that....), so that people can get on with their jobs and your employer can continue making money - add a comment for your dirty hack-fix. That way, when you come to re-write the code in a years time, a) you know why you've put that *really* odd thing in there, and b) you know the idiosyncrasies of both the system and your own code.

    No two ways about it, high-level, descriptive comments, are invaluable. Comments that say "increment x" are for script kiddies or those people in your CS lectures who couldn't code for toffee.

    Mines the one that says l33t hax0r on the back.....

  55. Anonymous Coward
    Anonymous Coward

    To comment or not to comment that is...

    /* Commenting has its place, but the person who dislikes commenting can quite easily remove the comments. */

    // Whereas those who like comments cannot conjur up comments, unless of

    // course as they read the code they wish to make their own comments.

    # I tend comment every function, method and class

    # but normally it will be a doc string style comment

    """I find it makes the structure stand out a little more.

    and helps with introspection techniques."""

    if (! a false proposition):

    # perhaps a comment is needed

    return -1

    else (let it stand for itself): pass

    ! Config files - I like to have my own comments in,

    ! though most developers are eager to comment here,

    ! as such these are prime candidates for a backup to a .distrc

    <!-- Bad code is bad code, no matter what commenting you add. I would prefer people did not waste too much time with comments, but if it makes them happy, we are only a;

    # We don't need no stinkin comments

    for k in *; do sed "/\/\//d" >> clean/${1}; done

    away for most code literate people to get at the pure, unadulterated, adult rated code. -->

    {- Editors come with folding as well, so comments can be hidden quite easily. -}

    ; If you want to document the code, then do so in another document;

    ; then you will see the added value and cost of doing so.

    ; It is quite good fun to document code, but it takes a fair chunk of time as well.

    -- With that said tools like pydoc, perldoc and introspection do work well

    -- with terse docstrings. Python's dir and standard .__doc__ are the type of

    -- clever-things you want to use your comments for.

    =HEAD2

    Comments are a tool - they are not going to magically make your code work, but they are useful for prototyping the main flow.

    Oddly, x++ is deserving of a comment; that is post increment not pre increment. If you are using post then you need to explain why, as soon as you do you will realise you should not be using it and refactor the code. Personally I blame people not getting the thought provoking naming of C++, but that is a gripe for another time.

    =CUT

    :wq

  56. Anonymous Coward
    Flame

    Separates the wheat from the chaff

    Good programmers comment their code and document their APIs. Semi-autistic fuckwits don't comment anything they write so that they can pretend that they're cleverer than the poor bastard who's just been recruited to the project and hasn't a clue WTF is going on and probably never will if he's smart enough just to quit on day one.

    I even had one retarded fuckwit complain that I wanted to put blank lines in my code to separate out logical blocks. He didn't like blank lines at all because it meant that he could get fewer lines on the screen and had to scroll more. Aw diddums.

    Bitter, moi?

    And another thing. How come I never seem to be asked to support the code written by some of the guys who've responded here and claim to document everything they do? Perhaps it's just the contractor's lot: I get hired when the project is in the shit precisely because they've hired the aforementioned semi-autistic fuckwits who've set out to prove how clever they were and discovered they weren't.

    Document your code based on the assumption that the next person to read it hasn't a clue what it does or why.

  57. Uzi

    The English Language vs The Programming Language

    If you're unable to make use of the rich vocabulary provided by the English language to create useful descriptions and comments that are easier to understand than code that you have written then either:

    a) You are a student learning how to code and thus writing code that has no value in the real world.

    b) You need to start taking English classes.

  58. wayne

    Extreme self-commenting code.

    Not going to read all this but:

    Naivety. Sure self-commenting code helps a lot, but the very best most efficient code can be extremely complex to read and understand (so comment where necessary). The smarty pants that wrote it, probably factored in one step what would take others several steps to do, so how do you expect others to suddenly get the insight he has in factoring to understand the self-commenting code. To further add to the problem, said smarty pants, if he did comment it, might think it is so obvious that his comments are so abstract that they don't help much either. So, comment where necessary down to the standard the competent/average programmer can understand (which ever is less). If you have below average programmers, comment down to their standard. And don't assume that a competent, or average, programmer bears an direct relation to your high standard of intellect.

    I tend to write down to a level of reasonable readability. But I had an engineering friend in uni, and she could immediately write something simpler than several of my attempts. Even in my VOS design documents, I sometimes write descriptions that seem to have obvious meaning, that I cannot fathom latter. The problem is we assume something is obvious because we already know the knowledge experience or answer, so we should never con ourselves that the meaning is so obvious.

    One of the problem I imagine, in this debate, is the common use of high level language. Where convoluted code can be inefficient code, and the assumption that truly efficient code can be written in that language, leading them to the false security that self-commenting code is more effective. Low level languages however, tend to allow a broader range of possible combinations of instructions and techniques to produce more efficient convoluted code.

    I know somebody that wrote an IDE hard disk interface driver in 100 instructions, or 100 bytes, I forget which. The code was not as readable to others as it might have appeared. Actually, the self-commenting code of this class of extreme programming is not so readable.

    It is like an ego thing, "yes, spend ten years of zen to understand my program.." The last rule is, why put people through all that pain to understand your code, when you can just adequately comment it for them to zoom in on the area of interest and change it. "Because I don't like commenting.." maybe, in other-words couldn't be bothered, it is somebody else's problem.

    When they can extreme pogrom in assembler so that 90% of programmers can easily follow what they are doing, then I'll believe some of these things.

    Wayne.

    PS Jame's lead looks promising.

  59. Justin Otto
    Paris Hilton

    I admit to over-commenting...

    I will on occasion comment lines such:

    // Increment loop counter

    ++x;

    Not always, but if each couple of lines has a comment it allows someone to read the comments of a function/method and then go back and read the code.

    Anyone who refactors live code to satisfy their own visual asthetic is creating testing obligations that might not be mitigated by their potentially assumption-driven unit tests.

    I wish them luck in their career, but do not want them to work for me.

    Paris because, even she could understand my code from the copious comments. :-)

  60. Philip Perry
    Alert

    Comments are as important as code.

    I work in I.T. in a state government agency in the United States. Most of my projects have business rules that are determined by regulations; these can be very dense and hard to follow. Once a software project is complete, it may not be touched for some time, and the next programmer who works on it may not know the regulations that apply. If I didn't comment all my code in great detail, there's no WAY anyone would be able to maintain it. Here's a sample:

    // On submission of a new set of filed schedules,

    // you MUST set the "submitted" and "amended"

    // booleans. Schedules may be edited or deleted

    // by the user until they have been submitted.

    // They may be amended after they have been

    // submitted but NOT after they have been

    // amended at least once. All submitted or

    // amended schedules must be frozen for

    // historical purposes. Don't screw this up or

    // we'll dangle you in the lawyer's cage!

    If I didn't comment my code, I think my boss would throw me down the stairs... We ALL read BOFH regularly. :)

  61. Anonymous Coward
    Unhappy

    I can't believe this...

    That such a debate exists at all is just a testament to the fearful and probably unfixable greenness of a certain set of XPers.

    Let a thousand lawyers feast. Hopefully on their messily shotgunned bodies.

  62. Turbojerry

    The author is very naive

    As many have said comments are incredibly useful in many ways, what hasnt been mentioned is when you need to point to supplementary documentation, for example when using an algorithm from Knuth or PhD paper or an SSE2 tutorial or when explaining hacks required when closed source you are linking to or hardware that does not behave as documented. That said comments do not always enlighten, I still would like to get my hands on who ever commented the SPICE source with such wonderful comments as // sanity check. Also comments are very useful for anyone joining a team, you can tell from quickly scanning the source who on the team knows their stuff and who hasnt a clue, and if management should start tossing out the good coders you know it's time to call the headhunter,

  63. Mark Pawelek

    The debate is not over

    Matt Stephens wrote: Clear code conveys the "what" and the "how", but not the "why"

    - But the point at which XP began was that essay, in 1992 by Jack Reeves: "What is Software Design?"

    The conclusion XP came to was that the code was the design, and, of course, comments are not part of the code therefore comments are part of the original design - which is not the current design.

  64. Tim Hustler
    Heart

    RE :I admit to over-commenting...

    Me too Justin. Works fine for me and those after me. I write code my mum could walk thorugh by just reading the comments

    When will people wake up and realise that programing is an art!! Where would more 'traditional' art be if a manual came out dictating how certain objects were to be drawn on the canvas?

    Extreme Programming has it's place, but other methodologies have their's as well. One coding style, one Language? Oh Please, we'd all be writing fortran in the console!!

  65. David Horton

    @Simon Neill

    ...are you serious or not? I thought you were joking at first but by the end of your post I was not so sure.

    Oh by the way out of uni less than six years, CS degree and mostly C# and Java programming so maybe I am biased but, just because you have been doing something a long time does not always mean you are any good at it!

This topic is closed for new posts.

Biting the hand that feeds IT © 1998–2019