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.

Page:

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

Page:

This topic is closed for new posts.