Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

What is an adequate amount of commentary on code?

Options
  • 09-04-2014 8:15am
    #1
    Closed Accounts Posts: 4,763 ✭✭✭


    I mean, how much is too much, or too little? Every time I look at someone else's code, or come back to my own code after a long break, all I see is a glob of random characters that I have a difficult time parsing, and so for my own sake I tend to be verbose in how I comment.

    Is this bad practice? Annoyingly much? Sure, it will vary by workplace, but as a rule is this fine?

    Example function:
    function addLightbox(obj) {
        // Append empty lightbox to whatever.
        // Best prepended to body.
        var divOpen = '<div class="';
        var divClose = '"></div>';
    
        var lbElements = [
            boxName + '-nav',
            boxName + '-txt',
            boxName + '-img',
            boxName + '-close'
        ];
    
        // Append lightbox to foo.
        $(obj).prepend(divOpen + boxName + '">');
        // Insert other elements.
        $(lbElements).each(function(i,e) {
            $('.' + boxName).prepend(divOpen + e + divClose);
        });
    
        // Insert nav elements.
        $('.' + lbElements[0]).append(divOpen + lbElements[0] + '-left' + divClose);
        $('.' + lbElements[0]).append(divOpen + lbElements[0] + '-right' + divClose);
    
        // Lightbox height.
        changeObjHeight('.' + boxName, $(window).height());
    
        // Blurb position.
        $('.' + lbElements[1]).css('margin-top', $(window).height() * 0.85);
    }
    


«134

Comments

  • Technology & Internet Moderators Posts: 28,791 Mod ✭✭✭✭oscarBravo


    That looks pretty good to me. I tend to be inspired by Python's PEP8 guide to inline comments:
    ...comments are unnecessary and in fact distracting if they state the obvious. Don't do this:
    x = x + 1                 # Increment x
    

    But sometimes, this is useful:
    x = x + 1                 # Compensate for border
    


  • Registered Users Posts: 1,987 ✭✭✭Ziycon


    However much is needed to clearly and concisely explain what's happening also no need to comment general code that any programmer should understand or use on a daily basis like assignments, basic calculations, loops etc unless there doing something that needs to be noted. Your commenting above looks grand.


  • Registered Users Posts: 2,030 ✭✭✭colm_c


    As mentioned previously, it's best to describe what the code does, not how it does it, as if you can't understand what's happening in the program then it's not very well written IMO.

    Also naming variables appropriately solves some of the readability issues IMO.

    e.g.
    var x = 100
    

    vs
    var lightboxHeight = 100
    

    Is always easier to read back and understand what's what.

    If you're paranoid (especially with client side programming, like js) you can always run i through an obfuscater.

    Also, not sure if that code below is real, but there's a bunch of optimisations that could be easily applied to make it much easier to read and understand 6 months later.


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,082 Mod ✭✭✭✭Tar.Aldarion


    If you named the variable LightBox You wouldn't need the likes of // Append lightbox to foo.
    I am a big fan of naming variables descriptively.


  • Registered Users Posts: 8,219 ✭✭✭Calina


    Looks okay to me.

    I'm a fan of documenting the why and again, using appropriate variable names.


  • Advertisement
  • Registered Users Posts: 2,015 ✭✭✭Colonel Panic


    I only use comments to apologise to future maintainers of my code.


  • Technology & Internet Moderators Posts: 28,791 Mod ✭✭✭✭oscarBravo


    I only use comments to apologise to future maintainers of my code.

    Ah, the "abandon all hope..." school of comments. :)


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,082 Mod ✭✭✭✭Tar.Aldarion


    Here thar be obfuscation


  • Registered Users Posts: 40,055 ✭✭✭✭Sparks


    The golden standard is Can another average programmer understand your code by reading it (and "Future You" is another average programmer for the purposes of the test).

    If yes, sufficient comments are in place. If no, then the other programmer is going to curse your name from here to whenever he or she is asked to give you a job recommendation in our tiny little industry.

    (Don't you love how source control means bad code is no longer anonymous?)

    Personally, I prefer people to err on the excessive side when commenting. It requires one keystroke to delete a superfluous comment line. It requires rather more to write an unwritten comment line when we find out a year later that it's badly needed...


  • Registered Users Posts: 27,033 ✭✭✭✭GreeBo


    oscarBravo wrote: »
    Ah, the "abandon all hope..." school of comments. :)

    // should never get here!


    Comment things that are not immediately obvious why they are happening or what is happening.

    Variable names and method names go a long way to this.


  • Advertisement
  • Registered Users Posts: 40,055 ✭✭✭✭Sparks


    GreeBo wrote: »
    // should never get here!
    Thank dog, I thought it was just me who'd run into that gem...


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,082 Mod ✭✭✭✭Tar.Aldarion


    I've seen should never get here comments in blizzard games. Heh.

    Svn blame is aptly named


  • Registered Users Posts: 40,055 ✭✭✭✭Sparks




  • Subscribers Posts: 4,075 ✭✭✭IRLConor


    GreeBo wrote: »
    // should never get here!

    Gah. Hate that.

    If you don't think it's reachable, then put your money where your mouth is and abort()/throw/raise/whatever.


  • Registered Users Posts: 2,015 ✭✭✭Colonel Panic


    IRLConor wrote: »
    Gah. Hate that.

    If you don't think it's reachable, then put your money where your mouth is and abort()/throw/raise/whatever.
    catch
    {
       // Pokemon!
    }
    

    Sorted.


  • Moderators, Society & Culture Moderators Posts: 9,664 Mod ✭✭✭✭Manach


    Try to use perhaps latin or Irish comments.
    The former has a conciseness and when I used the latter, there was an interesting discussion on language rights during the code review :)


  • Registered Users Posts: 20,892 ✭✭✭✭Stark


    I tend to be on the side of less is more. If you need comments to explain your code then your code needs to be refactored. Try using descriptive variable names and breaking out your code into smaller descriptively named functions.

    Problems with comments include adding code bloat (more scrolling to see what's going on) and comments not being updated when code is updated. Code errors will be caught out by compiler, unit tests, bugs etc. Inaccurate comments tend to linger and add noise.


  • Registered Users Posts: 40,055 ✭✭✭✭Sparks


    Stark wrote: »
    Problems with comments include adding code bloat
    Yeah, I'll take that all day, all night and twice on tuesdays, sideways, if the alternative is sitting there scratching my head at a chunk of code that makes no sense, several years after the guy who wrote it quit, with a deadline to debug it and a customer yelling down the phone about it.


  • Registered Users Posts: 7,500 ✭✭✭BrokenArrows


    Don't comment obvious code with what the code is doing. However, if the reason for that bit of code is unclear (And you cannot make it clear) comment WHY you are doing it.


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    If code has been clearly written, well indented and variable names are meaningful, you actually should not need any commenting as a competant developer should be able to read and understand it with ease.

    If you do comment the code, it should add to one's understanding of it, such as sign-posting different parts to say what is being handled there, e.g.
    // User log-out handled
    ...
    
    // Validation of user input
    ...
    
    Or briefly describing what a method/function does and perhaps it's params/return value (if not straightforward, e.g. an array in a specific format is returned).

    But this would me minimal commenting, which would be my preference, as I find excessive commenting superfluous.


  • Advertisement
  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,082 Mod ✭✭✭✭Tar.Aldarion


    If code has been clearly written, well indented and variable names are meaningful, you actually should not need any commenting as a competant developer should be able to read and understand it with ease.

    homereatingpopcorn.JPG


  • Registered Users Posts: 40,055 ✭✭✭✭Sparks


    If code has been clearly written, well indented and variable names are meaningful, you actually should not need any commenting as a competant developer should be able to read and understand it with ease.

    Ten years in industry, seven in academia, and I can count the number of lines of such code that I've seen on the fingers of one hand. While making a rude gesture with it. (I'd love to say all my code qualifies as this, naturally, but apart from a lack of people looking to beat my head in with a keyboard, I've no proof of that).

    (I'm not counting example code in books for this or reference code written to illustrate a point, I'm talking actual working code from real projects here)

    Frankly, I've had days on projects where if I got ten lines of comment per line of code, I'd fall to my knees singing the praises of flowers, trees and legal narcotics, regardless of the overcommenting because compared to undercommenting, overcommenting is like having too much money in your bank account...


  • Registered Users Posts: 2,021 ✭✭✭ChRoMe


    If code has been clearly written, well indented and variable names are meaningful, you actually should not need any commenting as a competant developer should be able to read and understand it with ease.

    In your bog standard CRUD apps maybe, complex algorithms, not a hope.


  • Closed Accounts Posts: 4,763 ✭✭✭Fenster


    Thank you everyone for your answers. The gist that I take away is that my commentary is fine, other programmers have the same problem with even their own code being illegible after a break, but I should continue to be wary of excessive remarks on elementary lines. :)


  • Registered Users Posts: 869 ✭✭✭moycullen14


    Came across one recently that made me wonder about the efficacy of commenting in general...

    It was a complicated java/hibernate criteria with projections, multi-table joins, aggregation, the whole nine yards. This stuff is hard to read at the best of times but this was way beyond normal.

    The developer had - thankfully - included included the generated SQL as a comment. This was a big help to understanding what he was trying to do. Unfortunately the comment was wrong. Usually you'd think that this is worse than no comment at all but because I could see what he was trying to do from the comment, it helped me understand the code.

    With modern API-driven development, the structure of the code is usually obvious. Where you want comments is where things are done in non-standard ways or where it is sufficiently complicated to warrant some explanation.

    Integration with SCM is key too. If you have to write an essay on a piece of code - and sometimes you do - tag the code in the SCM and the reader can access the description without cluttering up the code.

    This one made me smile
    Exception up = new Exception("Something is really wrong.");
    throw up;  //ha ha
    


  • Closed Accounts Posts: 4,436 ✭✭✭c_man


    I'm of the minimalist school of thought when it comes to commenting. I think in general if you find yourself putting a lot of comments in* then something is wrong be it the code, design or just your own approach.

    Sign, I'm muddling through a heavily commented module now on a bug fix. The vast majority of them are inaccurate.



    *excluding the likes of API headers and other common sense scenarios you'll throw at me.


  • Registered Users Posts: 1,922 ✭✭✭fergalr


    Everything that makes your source bigger is something extra to maintain - so every comment has a (notional) cost.

    So, basically, there's a point at which the cost of the comment outweighs the value it brings through increased clarity. At that point, don't add the comment.

    Where that point is depends on what you are writing, who you are writing for, lifetime of the project, how likely to comments are to be maintained etc.

    There's no one point answer, but the distribution of answers in this thread is pretty good I'd say.


  • Registered Users Posts: 40,055 ✭✭✭✭Sparks


    fergalr wrote: »
    Everything that makes your source bigger is something extra to maintain - so every comment has a (notional) cost.

    Of course, that argument doesn't have an actual answer buried in it, just a metric :)

    For example, unit tests add to the size of your codebase too, and there's research showing that code review is more effective than unit tests for finding bugs (in terms of how many it finds). So do we stop writing tests for code? :D


  • Registered Users Posts: 1,922 ✭✭✭fergalr


    Sparks wrote: »
    Of course, that argument doesn't have an actual answer buried in it, just a metric :)

    For example, unit tests add to the size of your codebase too, and there's research showing that code review is more effective than unit tests for finding bugs (in terms of how many it finds). So do we stop writing tests for code? :D

    When the cost of maintaining the test exceeds the value it brings in terms of code correctness, and ability to make changes with confidence, etc. then the test should be not written.

    So, yes, basically.

    There's a cost to writing each test, and to having each test sitting in the codebase, and to every time a programmer thinks "I could refactor that, but then I'd have to update all my tests."

    Complexity is one of our main enemies. Every framework, tool, scaffolding, test, harness, comment, and SLOC has a cost in terms of complexity. Each such component of the system must either provide benefit exceeding its cost, or be deleted.

    Where that balance point is will depend on a bunch of factors, but we should remember that we're always trying to strike that balance.
    There's definitely a 'test usefulness' threshold, below which we just shouldn't write that test.

    I know my estimate of that threshold seems to be much higher than a lot of people involved in, say, TDD.


  • Advertisement
  • Registered Users Posts: 27,033 ✭✭✭✭GreeBo


    fergalr wrote: »
    When the cost of maintaining the test exceeds the value it brings in terms of code correctness, and ability to make changes with confidence, etc. then the test should be not written.

    So, yes, basically.

    There's a cost to writing each test, and to having each test sitting in the codebase, and to every time a programmer thinks "I could refactor that, but then I'd have to update all my tests."

    Complexity is one of our main enemies. Every framework, tool, scaffolding, test, harness, comment, and SLOC has a cost in terms of complexity. Each such component of the system must either provide benefit exceeding its cost, or be deleted.

    Where that balance point is will depend on a bunch of factors, but we should remember that we're always trying to strike that balance.
    There's definitely a 'test usefulness' threshold, below which we just shouldn't write that test.

    I know my estimate of that threshold seems to be much higher than a lot of people involved in, say, TDD.


    Wouldnt a test thats difficult to maintain imply that the code its testing is also difficult to maintain....and having a test is thus a lovely warm fuzzy blanket?


Advertisement