150

I've worked in shops that produce life critical software and I've dealt with commenting rules that were meant to keep the code readable and potentially save lives. In my experience though the requirement becomes a brain dead chore to be ticked off of a checklist and doesn't help me stay focused on writing understandable code. It also distracts my peer reviewer from having a more meaningful conversation with me about how to make the code easier to understand.

I've also graded student code that had no comments and seen why they should be marked down for neglecting them.

I understand that using good names, keeping structures simple, functions short, and modules focused will keep the code understandable enough that comments can be minimized.

I also understand that comments should explain why the code does what it does, not how.

Given all this is it even possible to write good coding standards that capture this idea? Ones that will be relevant in a peer review but won't turn into a mindless checklist activity that produces notes no more helpful than: "You forgot to comment on line 42".

An example of the kind of code this rule might require when treated as a line in a checklist:

/* Display an error message */
function display_error_message( $error_message )
{
    /* Display the error message */
    echo $error_message;

    /* Exit the application */
    exit();
}

/* -------------------------------------------------------------------- */

/* Check if the configuration file does not exist, then display an error */
/* message */
if ( !file_exists( 'C:/xampp/htdocs/essentials/configuration.ini' ) ) {
    /* Display an error message */
    display_error_message( 'Error: Configuration file not found. Application has stopped');
}

If it is possible to express this properly in a standards document, and it might simply not be, I'd like to capture an idea along these lines:

Consider a comment for every line, sequence, statement, section, structure, function, method, class, package, component, ... of code. Next consider renaming and simplifying to eliminate any need for that comment so you can delete it. Check in while comments are rare. Repeat until deadline. Then repeat some more

candied_orange
  • 108,538
  • 21
    Comments are not for extended discussion; this conversation has been moved to chat. – maple_shaft Nov 23 '16 at 17:04
  • 36
    “Comments are not for extended discussion” even truer for code comments. :) Those /* Display an error message */ comments are horrible and actually impact readability. – Andrea Lazzarotto Nov 25 '16 at 17:25
  • We need our IDEs to have options for hiding comments. Maybe an option for both block and inline comment hiding separately. This way you have the best of both options. Put lots of comments in, but have the option to hide them to keep the code looking clean and uncluttered. – Doug.McFarlane Nov 25 '16 at 19:49
  • 1
    @Doug.McFarlane I thought that should exist for vim. Of course it does at both file and block levels - http://www.rtfm-sarl.ch/articles/hide-comments.html ! – Michael Durrant Nov 25 '16 at 21:00
  • 1
    Also toggling - http://stackoverflow.com/a/11842371/631619 – Michael Durrant Nov 25 '16 at 21:01
  • The coding standard should mention that comments are meant to add information. Check your examples above. There are many comments that add absolutely no information that is not clearly there already (e.g. if you don't know that exit(); exits the application, you have no business reviewing this code). – Tom Nov 27 '16 at 07:50

17 Answers17

174

Michael Durrant's answer is IMHO not bad, but it is not literally answering the question (as he admitted by himself), so I'll try to give an answer which does:

I also understand that comments should explain why the code does what it does, not how.

Given all this is it even possible to write good coding standards that capture this idea?

Obviously you can write a checklist for your code reviews, containing questions like

  • "if there is a comment, does it explain why the code does what it does?"
  • "is each line of the code - in its context - either self-explanatory enough that it does not need a comment, or if not, is it accompanied by a comment which closes that gap? Or (preferably) can the code be changed so it does not need a comment any more?"

If you like, you can call this a "coding standard" (or not, if you think the term coding standard should be reserved for a list of braindead rules, easy to answer if they are fulfilled or not, how the formatting of the code should look like, or where to declare variables). No one hinders you to have the focus of your checklist on semantical questions, instead of going the easy route and put only formal rules into it.

At the end of the day, you should be sure your team needs such a checklist. To apply such questions you need programmers with some experience as reviewers, and you need to find out if it will really improve the readability of the code in a team of experts. But that is something you have to work out together with your team.

Doc Brown
  • 206,877
  • 49
    Who downvoted this? This is the answer for critical software development. This is a different world compared to where most programmers work. In these worlds, a coding standard that calls for that every single line of code to have its own comment is not the right answer. Neither is forgoing comments. OTOH, making comments subject to code review is exactly the right kind of standard for critical software. It makes for more reviewable and maintainable code, but this comes at a cost. That cost pales compared to multi-million dollar lawsuits that have resulted from poorly written software. – David Hammen Nov 20 '16 at 22:05
  • 4
    wise answer. if we could find genuine rules for coding, we would not need programmers. we could just have the machines code. it could happen! :( –  Nov 20 '16 at 22:29
  • 4
    @DavidHammen: thanks for your comment. Actually, I think this does not only apply to "critical software development". Every piece software which is maintained and evolved over years, often by different people, will benefit from beeing understandable for the next maintenance programmer. – Doc Brown Nov 21 '16 at 07:10
  • 5
    This is good advice for any coding, not just code maintained by different people. Even if you are the only one using a script/program, the future you who has to modify the code in a year's time will appreciate the clarity (and the time saved by not having to decipher opaque code). – Anthony Geoghegan Nov 21 '16 at 10:24
  • This is the correct answer. For me it's simply: given some code that is obtuse, it's good to add a comment explaining it but it's far better to refactor it to make it easy to understand. In rare situations this is not possible and more often there may not always be time. The main reason I use comments is when I have had to write seemingly silly or nonsensical statements to work-around bugs in a library. – JimmyJames Nov 21 '16 at 14:35
  • 5
    Could you edit "currently most upvoted answer" to something more objective? Not every reader is going to know the vote history of these answers. – candied_orange Nov 23 '16 at 01:05
  • @CandiedOrange: sure. Though, when I wrote this, I thought it was very unlikely that Michael's answer would leave its first place (and probably it won't). – Doc Brown Nov 23 '16 at 06:36
  • 1
    @DocBrown yes but for all anyone ignorant of the voting history knew you were talking about JacquesB's answer at the time. It just creates a puzzle to solve that distracts from your otherwise excellent answer. – candied_orange Nov 23 '16 at 06:40
  • I can understand why this is down voted. After reading it a few times it amounts to saying this; "You shouldn't drink and drive, but if you need to, this is how you drive drunk. Step 1: ..." – Andrew T Finnell Nov 23 '16 at 16:03
  • 1
    @AndrewTFinnell: sorry, but I don't understand your analogy. Can you explain what you mean? – Doc Brown Nov 23 '16 at 16:13
  • @DocBrown It is my understanding that you're proposing that a Coding Standard which requires certain comment rules, regardless of what those rules are, is not valuable as you'd need experienced engineers to assess that value. And if you had good engineers then what's the value of extraneous comments? If that is incorrect I apologize. So that being said, you then proceed to explain how to do the opposite of what you've suggested. With the suggestion being that it shouldn't be a Coding Standard. – Andrew T Finnell Nov 23 '16 at 16:21
  • @DocBrown The analogy I picked was in poor taste. I hoped it would convey sentiment and not literalness. In a way, this is great, because it proves the point about who derives value from which specific ordering of words prefixed with a //. It can't be qualified. – Andrew T Finnell Nov 23 '16 at 17:01
  • @AndrewTFinnell: ok, you had some problems with my last paragraph, maybe it was giving a wrong impression about what I meant. See my edit. Better now? – Doc Brown Nov 23 '16 at 17:04
  • @DocBrown I realize it'll seem insincere, but yes I do like what you reworded it to. In this question that is trying to determine whether one can accurately document a standard way of describing something, it's all in the minute details. Your change enhances your question tremendously in my mind. This sort of proves my previous point to others. You took the time to look at what you wrote and decided to change it. Others did not change their answers. Imagine if you had to be approved by 10 of the people writing on this question before your answer could even be posted. You may have moved on. – Andrew T Finnell Nov 23 '16 at 17:10
154

Major anti-pattern leading to poor quality code with less clarity

btw readers, the title was originally "comment every line of code?" and you can imagine the instinctive reaction of many of us, myself included. I later retitled to the longer more accurate title.

At first, reading your question I thought, yuch duplicate stuff in comments , but ok, maybe if you have enough strictures on reviews by multiple people... but then again: people makes mistakes, fail to notice inconsistencies, etc. and over time there will end up being differences. On reflection I think the problem is much larger:

Developers will tend to write worse code. They will use more cryptic names and structures because 'its explained in the comment - see!'.

Consider:

living_room_set = tables + chairs.

Now consider:

set = tbls+chrs # Make the set equal to the table plus the chairs

You not only have both more cryptic names and more to read, you also have to look back-and-forth, look at code, what is a set? look left at code, look right at comments, what are tbls, look left at code, look right at comments, what are chrs, look right at comment. Yuch!

Summary

Develop or enhance a commenting standard if you are forced to in your current position as a developer (As a former COBOL programming I've sure seen big ones!) but spent as much of your time, energy and passion arguing against the commenting anti-pattern using the arguments:

  • Code and Comments get out of sync with each other when only one is changed

  • Comments may describe what one person thinks but may be wrong and thus cover up bugs

  • Code becomes harder to read

  • Good code becomes harder to write

  • Tendency to have use more cryptic names

  • Excessive characters to read in code and comments

  • Different editors use different styles

  • Requires higher English language proficiency than just coding

  • Takes time and resources and subtracts from long-term value *

Plus argue for better code without such comments,- in fact have a standard(!) - all variable names must be full_english_words - there's one! So use that 'standards' energy towards the standards of well written code and tests.

One of the two hard problems is naming things - don't side skip the problem with comments.

Given that one of the other problems is premature optimization and that optimization in general can leads to obscure 'why this way' code, this is one area where explanatory comments for apparently poor code may be beneficial although the above caveats still apply.

* tomorrows code

  • 8
    I don't believe you answered the question. The question is not about having comments on every line. It is asking how to tell developers to comment code without causing them to comment every line. – hichris123 Nov 20 '16 at 22:58
  • 7
    Yeah I am not answering the specific standards question but instead trying to help folks not go down that route. So this may not be the answer to the specific question but does contain valuable advice that is hard to lay out in a comment. – Michael Durrant Nov 21 '16 at 00:34
  • Added a little bit to allow for such standards if forced but to argue against them. – Michael Durrant Nov 21 '16 at 01:41
  • 1
    What is the other hard problem? – David says Reinstate Monica Nov 21 '16 at 16:13
  • 21
  • I once worked for a place that mandated all vowels be removed from variable names because 20 years ago the compiler mandated 8 character variable names. Even though for 10 years you could have bigger, they didn't want to break the consistency going forward. Unless it was to tack on the Hungarian, then you could go over... I'm so glad I'm not coding there anymore... – corsiKa Nov 21 '16 at 17:12
  • Fun fact: In assembly language, most (but still not all) lines should have comments explaining the semantic meaning (and not repeating what the instruction mnemonic + operands already say). Sometimes there's still nothing to say about obvious stuff like call printf, except maybe to summarize the args that were set up earlier. Using macros to make up meaningful-name aliases for registers would have different (worse) downsides than needing to keep a lot of comments in sync. – Peter Cordes Nov 22 '16 at 01:42
  • In my experience I see all the time that the freedom not to comment leads to poor quality code with less clarity, the obvious reason being that not having to explicitly declare the intention of the code allows developers to throw in code that does something that they themselves are far from sure that is what the code should do there. And I have never ever seen one case where freedom not to comment actually resulted in better code (I mean in practice, not in a book). Not being religious here, just applying my honest observation of reality. BTW have you a source for the anti-pattern claim ? – SantiBailors Nov 22 '16 at 10:54
  • I have about the same years of work experience as you and I very consistently observed exactly the opposite, be it where I worked, where friends of mine worked or at the customers where I was sent. However I see from your tone that the intentions of my comments did not come across right so let's not elaborate further. But a sincere thanks to you, because - even though I cannot imagine being so lucky as to find 4 companies in a row that believe in quality and practice good code for real (I didn't get the checkbox metaphor, sorry) - thinking that they are there is really refreshing. – SantiBailors Nov 22 '16 at 16:22
  • no problem. I'm lucky enough to work in newer smaller start-up style companies for the last few years so that is a huge influence I'm sure :) – Michael Durrant Nov 22 '16 at 22:34
  • @hichris123, I love your one sentence summary of the question, but I factually didn't get that idea at all out of reading the actual question. If you really think that's what it's about I think you should suggest an edit. – Wildcard Nov 23 '16 at 02:30
  • Downvoted for not answering the question. – user253751 Nov 23 '16 at 05:03
  • I believe the person answering this is being polite by agreeing that they didn't answer the question. This answer does address his concerns. The issue here is that we're all trying to deal with subjective vs. objective tests. – Andrew T Finnell Nov 23 '16 at 15:29
  • fyi http://softwareengineering.stackexchange.com/questions/145574/recommendations-for-teaching-junior-programmers-good-coding-style/145595#145595 – Michael Durrant Nov 23 '16 at 20:32
  • 1
    Each of your reasons to avoid comments can be countered but StackExchange doesn't allow long enough comments (heh) for me to address them all here. Simply: overcommenting is like voter fraud: it does happen, but very rarely; when is the last time you actually saw it happen? Writing good comments should not be simply an afterthought; if done correctly, it helps the development process. Yes, it takes resources, but the payoff is better code. You will never be able to get the same bang for your buck by sacrificing comments for a better variable naming standard. Yes, commenting every line is nuts. – kmoser Nov 27 '16 at 02:10
  • overcommenting. yes I have seen 2 or 3 folks do this. The mountains they wrote made up for their rarity. If the development process cares about good comments.... it can care enough to make those comments part of the code itself. Rules against comments without corresponding care and attention paid to code reviews and high quality code is not good. Having both in place in what I think folks should strive for.
  • – Michael Durrant Nov 28 '16 at 19:28
  • Longer names aren't always better. Sometimes, abbreviation is a boon. foo.v = PI * pow(foo.r,2) * foo.h in a pile of code is easier to scan and understand than volume_of_foo = ratio_of_circumference_to_diameter * raise_to_power(radius_of_foo, power=2) * height_of_foo. – Brandin Feb 27 '17 at 07:50
  • 'pow' hmm lets us, ah raise_to_power, got it. and h?... ah yes height. I prefer to leave short-term memory free for other stuff. – Michael Durrant Mar 27 '17 at 12:43
  • May I conclude what we need? I think a good document is needed if comment of each line is not necessary. Finally, it becomes, we try our best and use all tools (drawing, video, doc, comments, etc) to explain our code, right? – skytree May 23 '23 at 05:12
  • Lots of good comments here. Not seeing solutions to the fact that not matter how good or bad comments are... they get out of date because they are manually maintained. Then they can have negative value. Think about the future not just the moment. – Michael Durrant May 23 '23 at 09:42