Hacker News new | past | comments | ask | show | jobs | submit login
I've never seen a language's style guide recommend avoiding comments before (haskell.org)
166 points by vs2 on July 23, 2014 | hide | past | web | favorite | 191 comments



Avoiding comments that do what your code should be doing is common practice, and I think that's what this style guide is recommending.

Comments are useful to describe __why__ you're doing something, often when you are not able to change the unexpected behaviour. Whenever I build an API library, my code is littered with comments like "Acme Corp API requires this happens before that" with a link to that bit of the API documentation.

Here's a C++ example about "documenting surpises" (taken from Steve McConnell's Code Complete:

    for ( element = 0; element < elementCount; element++ ) {
        // Use right shift to divide by two. Substituting the
        // right-shift operation cuts the loop time by 75%.
        elementList[ element ] = elementList[ element ] >> 1;
    }
And a Java example:

    /* The following code is necessary to work around an error in
       WriteData() that appears only when the third parameter
       equals 500. '500' has been replaced with a named constant
       for clarity. */

    if ( blockSize == WRITEDATA_BROKEN_SIZE ) {
         blockSize = WRITEDATA_WORKAROUND_SIZE;
    }
    WriteData ( file, data, blockSize );
He also gives a whole list of situations in which comments are a bad idea, and it's similar to the OP.


Completely agree :) In some cases I prefer to wrap it in an aptly named function, but in other cases I prefer the whole algorithm to be in a single function, making comments a very useful tool for "naming".


in other cases I prefer the whole algorithm to be in a single function

A modern compiler can inline most of your function calls if you like. That way you can factor the code appropriately for both concerns.


Putting the whole algorithm in a single function isn't for the compiler's benefit but for the reader's. Especially in languages with side effects any function call you need to analyse takes time and then you need to come back to the main function and remember your mental state.

Please note that in many cases putting an algorithm in a single function is the wrong choice but there is also a cost in splitting it.


The point of Haskells type system though is that those annotations tell you most if not all of those things, they're a form of documentation that is very powerful and designing your types clearly makes it even better.

Plus your annotations are updated! Comments wither and die.

[Edit] to be clear, if there is something going on that would cumbersome to "document with types" i just write comments. There's also a place for function description and example.


That's the only thing that must be said about this topic.

As a rule of thumb, if I've thought more than 20 seconds about what a particular section of code has to do, I comment it.


Of course everyone thinks they always write good clean code and therefore don't need comments to elaborate on what the heck is going on.

Unfortunately, having been doing this trade for 30+ years, I've found most people write crappy code in a hurry to try to hit some deadline based on incomplete requirements and confusing business rules. A few precious comments stuck in there can help the next guy, months or years later, figure out what the heck your original intent was or why a block of code exists at all.

As I get older, I find it helps me remember what I was doing.

One of my software developer friends was fond of saying: "the worst code I ever saw was my own!"

YES if your code is clean and elegant and well named and clear you don't need to explain anything in common language.

YES you should strive for such.

However, the REALITY is your code sucks and no one is going to want to have to figure out what the heck you were doing. A few comments would really help.

The next reality is that the typical developer may be literate in a dozen or more languages and the language du jour that you coded so elegantly in has fallen out of favor and no one remembers those dusty corners you so beautifully exploited to make something work.

Comments would help even more if you learn to use some basic grammar and spelling when you create your comments. (It doesn't have to be literature, but try to make your comments as readable as you think your code is - please!) Nothing will turn another developer off to trying to decipher your code than a few comments that make you look like a moron.

Style guides that eschew comments, IMO, are counterproductive. They feed on the developer's ego and disregard reality.

Comments cost essentially nothing to add to your code and can save it from an early death and complete refactoring by the next guy who comes along.


I wonder where the idea comes from that people that write code that's hard to understand, will write comments that are easy to understand.


Good programmers sometimes have to do weird things.

Leaving a note about that weird thing is probably a good idea.


I agree with this, but I also think it's better if you can avoid the weird thing.


In my experience:

A novice programmer will just do the weird thing (no comments).

An intermediate programmer will spend twice as much time as they should, trying to think of an elegant solution, before doing the weird thing anyways (and maybe leaving a comment).

A good programmer will just do the weird thing, leave a comment, and move on.


I somewhat agree, except possibly for the "should". I think that trying to think of an elegant solution (and then accepting that you can't, where appropriate) is an important learning process. Of course this depends on context; spending time on learning is sometimes inappropriate.


I agree with that. Perhaps more accurate phrasing would be "more time than the seasoned developer would have". Part of getting to the third stage is learning those types of lessons during the second stage - which only comes with experience.


    -- NOTE
    -- This is called by the database-level DDL trigger.
    -- Do not drop it. Do not break it.
We don't have a dev/qa environment, and tend to be a bit... lax about change management. There are a few pieces of code that this is particularly unsuitable for.

    function f_soundex (p_in varchar2) return varchar2
    is
    -- [name of specific source file from one of our other systems]
    -- If the first (kept) letter has the same code as the following letter,
    -- a proper Soundex ignores that following letter. The [other system] soundex
    -- keeps it.
Sometimes it is necessary to do weird things for compatibility reasons.

    // See http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98335
    // Apparently, DestroyHandle doesn't get called properly when a control is disposed. Since this
    // makes Invoke() hang, we have to fix it.
Sometimes external libraries/frameworks have bugs to work around.

    /* Don't let things scope to the repeat block. Even when they aren't used, they
       make the end statement slow. read-record.i has strong scoping for the data
       tables, and everything else is lifted to procedure scope. */
Sometimes there are performance reasons for doing things in a particular slightly odd manner. Sometimes there are correctness reasons (as with a 9-line comment earlier in the same program as this last example).


Well, native language and programming languages aren't the same thing and you express yourself differently in them. That's basically a given.

But comments are most useful when they explain why something is being done, not what's being done. The latter is usually simple to work out with even the most hideous code. But if I don't know what you were trying to do or why you did something in a particular way, seeing what you did alone may not be all that helpful, especially when maintaining code.


native language and programming languages aren't the same thing and you express yourself differently in them

Indeed. However, when developing software I'd expect that the responsibility is first to express yourself clearly in code and only second to express yourself in prose, which means if you're taking very much time to do the latter it's time that could be spent doing the former.


The idea is that if you do a little bit of the latter now, you will save yourself or someone else a lot of time doing the former later.


But all too often, people who write hideous code sprinkle it with comments that merely explain what is done, at the lowest level.


Yes. The industry is full of hacks. I don't see how that's a problem with comments though. They're going to write hideous code with or without comments.


The problem is that comments visually bloat the code and make it harder to understand. Bad code with useless comments is worse than bad code with no comments. And that's not even counting comments that are out of date and misleading...


And bad code with good comments is more useful than bad code with no comments. It strikes me that replacing "comments" with "tests" in much of our thread would lead to the same outcome. I guess we're just going in circles on this one.


> The problem is that comments visually bloat the code and make it harder to understand.

That's a good reason to avoid breaking up logical blocks of code with comments.

Its not a good reason not to comment.

> Bad code with useless comments is worse than bad code with no comments.

That's a good reason to have code review (which includes review of comments) to ensure that there is neither bad code nor useless (including out of date or misleading) comments.


I think because most people find written english easier to produce than clean code.

Comments have certainly aided me enormously in navigating very large, sometimes crufty, codebases.


I don't mean this negatively, but in my experience as a high schooler and in college, the programming crowd tended to be lacking in written (communication) skills. This is certainly a huge blanket statement, but for younger programmers today I think the stereotype has at least some truth.


There are some people whose code I'd be terrified to maintain, if their code/comments are anything like their text messages.


> Comments cost essentially nothing to add to your code and can save it from an early death and complete refactoring by the next guy who comes along.

Whatever their benefits are, this is not true at all. Comments are expensive to write and maintain. They are VERY VERY expensive to maintain because there is no automated way to test them.


Disagree.

Reason: In Software Archeology (a.k.a. maintaining legacy code) you are often happy to get any kind of clue as to what went on inside someones head. Maybe they saw an edge case?

Of course you should write self-documenting code with variables and function names that explains most of it but when you either have to

1. factor out a new function

do_this_to_fix_that_weird_thing(weird state)

or

2. have to add a line

state == weird ? fix = fix+1:continue // weird is a weird state that sometimes occurs even though vendors api docs says otherwise.

please think twice.

Outdated comments are a problem but very often a problem I'll happily deal with compared to not having them at all. If a comment doesn't make sense you can also try checking VC history.


I will take 3

3. fix_bug_that_occurs_even_when_api_docs_say_otherwise(weird)


I've certainly come across situations where the code and the comment don't line up, but that seems to arise from laziness more than anything else. If the comment is directly attached to a region of code, most developers I've come across will process both at the same time. The area where I see it fall apart most commonly is with javadoc-style comments. Most IDEs will even flag these issues, but they're often ignored.

A comment on its own isn't inherently harder to maintain any other piece of code or documentation. Sure, it's not zero cost, but I find more often than not they exceed the cost associated with not commenting.


You're not wrong but you're isolating the cost of commenting a certain piece of code. It's really about the net time investment. If you create comments the idea is that code maintenance in the future is easier and/or introduces less risk of introducing new bugs (and you'll agree those are even more expensive to resolve). That said it remains a bit of a subjective discussion.


Forgive my ignorance, but why and how would you test a comment? They don't do anything, there is no instruction for the machine to understand or run.


He's referring to the problem of comments becoming out of sync with the code they're referring to. Not everyone updates comments as they update code.


And those people deserve a special place of torment all their own. How hard is it really to update, or at least delete comments that are no longer relevant when you modify the code?


It's not that it's hard, it just may not be apparent that you need to do so.


The comments are meant to be read and used to understand code. So you must test them like any other artifact to ensure that they are a net positive and not a net negative. Programmers make mistakes, which hopefully fail a test or at least cause a crash. Because comments can't be executed, neither of those will happen; they have to be verified manually


Isn't that fairly easy to do during a code review?


Only when all comments only refer to local information. There is nothing to check that the comment in that other file that refers to this code was correctly updated.

Some system of backrefs could handle this, of course, but I'm not aware of anything in use...


> Only when all comments only refer to local information. There is nothing to check that the comment in that other file that refers to this code was correctly updated.

The only time a comment should refer to non-local information is to document an assumption or basis of the local code, which is still correct information about the local code as long as it is the assumption/basis of the local code, even if the assumption is (or later becomes) false.

Of course, it would be useful to have a way to verify the information about the assumptions to see if they have become false, but that's not about validating the comment, that's about validating the code it comments, since if the assumption is false, it is quite likely that the code needs to change (and this may not be something that unit testing the local code can discover, as such comments often are not about correctness but about choosing a less-than-obvious alternative correct approach for optimization, or to work around a quirk of the code being called, etc.)


I'm not sure I disagree. In practice, though, I certainly encounter comments communicating nonlocal information ("This is used in ..."), and of course these are the least likely to remain accurate. "All comments is local" is something we should start drumming into people - I don't think anyone ever said this to me explicitly.


Sure, code review is a very manual approach.


Yes, what I mean is, if you're doing code review then there's virtually no additional cost - you're looking over the changes anyway. It doesn't matter that the process is manual if you're already doing it. If you're not doing code review, then you perhaps either have some organisational issues or you have coworkers who are sufficiently responsible that you can trust them to do basic code hygiene work like keeping comments up to date.


I think comments would be more difficult to review than code, since you'd have to carefully make sure they are meaningful by examining the code, without the context of the programmers involved. Alternatively, you could add comments during code review to document the review and basically redo the comments on each review...maybe.

Comments also break flow and get in the way of code reading, but could probably just be hidden during review.


> I think comments would be more difficult to review than code, since you'd have to carefully make sure they are meaningful by examining the code, without the context of the programmers involved.

Actually, that only makes them hard to review if you are trying too hard, which defeats the purpose of reviewing comments -- if it is hard to validate the utility of a comment without the context of the programmer involved, its a bad comment and needs, at a minimum, to be clarified.

After all, the whole point of a comment is to communicate information to a future person who lacks the context of the programmer involved.


It's manual whether with a tool or without. We like using a tool because it automates the process. We find teams are more thorough in their reviews with a tool. We're also distributed, so it helps with collaboration too.


Brings up an interesting point about perhaps using natural language processing to determine correctness of a comment. That would be prettty cool.


If you could use NLP to verify the comment, then what would the point of the comment be? Comments are for those aspects of a program that are invisible to the compiler and IDE, the intent.


Maybe my view of NLP is more sci-fi than reality, but I think you're missing what I meant. If you can use NLP to prove that your comment - ie the intent - which IS invisible to the compiler and IDE, then that might be cool. Practical, probably not. But I'd still be very impressed at the implications if this was possible within some error margin.


Then you will read the comment that says to do one thing but the program will do a completely other thing. I don't see any problem, do you?


That's why good comments are about explaining WHY you're doing something, or HOW to use the code, and possibly making the code itself clearer but only if there's no way to do that by introducing better variable and method naming.

Comments are highly valuable but like any tool they can be abused, or done in such a way that they don't make things better.


The point is that comments can become out of date, and there's no automated way to enforce they stay up to date.


> Style guides that eschew comments, IMO, are counterproductive. They feed on the developer's ego and disregard reality.

To be fair, the style guide that's linked to doesn't actually say not to write comments. It says that if you're going to write a comment, think twice. Maybe you can make the code clearer instead.


More than the language du jour, many of us evolve. The way I wrote in code in language X today is a bit different than how I wrote it 6 months ago. This is especially true when first starting a language. Then, as I've worked in more languages, I've been exposed to better techniques and those influence how I think about problems.

At any given time I'm writing code as clearly as I can given my experience and body of knowledge. It also is representative of my exposure to and familiarity with the problem domain at that point in time. As these things evolve, my older code ceases to be as clear as I thought. It may very well not be the way I'd solve the problem again.

And that's before I need to start making changes to code clarity to satisfy a hard requirement (reduce memory usage, cache values, tighten up performance, etc.).


Agree perfectly. "Your code should be self-documenting" is one of the memes that give you an excuse for being lazy. While true in the ideal case, very few programmers are able to (or even in a domain where it is possible to) write code that documents itself.


It's not at all an excuse to be lazy. If your code isn't self-documenting, you need to document it. But rather than spending your time doing that, how about you improve the code instead?

Are you looking for an excuse to be lazy? How about "I'll just put a comment in there and not worry about it"...


How can you write clean, simple comments if you cannot write clean, simple code.


It's not always a matter of being able to write clean, simple code. In fact in my experience ability is hardly ever a factor. You may not have enough time, you may have to use complex counter-intuitive APIs, the business requirements might be unclear, the algorithm might have complex components that are hard to convert to easy to read code, etc. There are literally dozens of reasons why code might not be "clean and simple" and not of all of those reasons are associated with developer know-how. Whenever this discussion comes up it tends to be a "theory vs real world" sort of discussion.


I'm in a field (healthcare integration) where vendors constantly break spec or handle things in a quirky manner.

The actual code I work with is fairly straightforward and easy to understand functionally. I can understand the what of pretty much any of the code my organization runs in short order.

But the why is vital. This week I've implemented things for reasons I won't remember in six months. Simple, easy to understand code. I've also been fighting with another system that predates me. I can see that it's modifying the original message to map particular values elsewhere downstream, but I have absolutely no idea why or which downstream system is expecting them. I've lost hours trying to track this down when a line or two explaining WTF the piece of code exists would have told me exactly where I needed to look.

Yes, your code should be understandable and self documenting to some degree anyway. But your code doesn't exist in a vacuum, and can't document what exists external to it.


My sentiments exactly.


TFA is not arguing against writing comments, it's arguing againts writing obvious and meaningless comments. I'd much prefer no have no comment to 'getA' method than full blown comment saying 'ruturns B', just because before refactoring method was called getB, and the comment was meaningless then, and wrong now.


I think rotten's response to this is that it's easy to think that your code is clearer than it really is. I think we can probably all agree with what you've said about your example, but in the real world, the decision may not always be so obvious -- either because it is genuinely a harder question, or because of an oversight. This being the case, maybe it's better to get in the habit of writing even stupid comments (within reason) as well as (of course) eliminating unexpected behavior when possible. This is merely a concession to reality: your code will rarely be perfect, and you will not always have the time/resources/inclination to polish everything the way you might like. But at least if you write a comment, future readers of your code won't be at a disadvantage in fixing your mistakes.


In this sense, the article doesn't add much value. If you're just saying, "Avoid unnecessary comments" you're in the same state of truisms as "Write quality code" or "Try your best".


To be fair the article doesn't just say "avoid unnecessary comments" it actually gives some pretty concrete examples of less than ideal comments and ways in which you can make the need for a comment in that situation unnecessary. The TL:DR; of the article is essentially compile time errors are better than comments for preventing bugs so use the Type system if you can to encode your invariants rather than simply trying to document them in your code. That said, you can't always do that for various reasons so in that case it's perfectly reasonable to put comments in documenting that, but in that case at least try to capture the intent behind the code, not simply rehash the mechanics of how the code is accomplishing that. E.G. "returns a count of how many users have been flagged in the Foo system", instead of "returns user_foo_count".


Hahah, I so much agree!

I also think you should target for 0 comments in an ideal world. Every time I write a comment I remind myself, can't you really write this in a more obvious way?

But reality is that exercise requires time that you don't always have


Well that is ... sad. I have not been around for 30+ years and I see good code on a weekly basis. Maybe you should consider changing something in your environment. I assure you it is possible.


Maybe he 'sees' bad code that you would consider 'good' code. This can be a bit subjective, and also he has much more experience than you ...


Maybe. It's still sad.


  A few precious comments stuck in there can help the next 
  guy [..]
More than spending that time on improving the code?


Do you really think the time spend writing a comment is comparable to improving the code? Personally, I can't think of an occasion where that would have been true.


Robert C. Martin's Clean Code book has a great section on comments:

- The proper use of comments is to compensate for our failure to express ourself in code. Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not a cause for celebration. So when you find yourself in a position where you need to write a comment, think it through and see whether there isn’t some way to turn the tables and express yourself in code.

- The older a comment is, and the farther away it is from the code it describes, the more likely it is to be just plain wrong. The reason is simple. Programmers can’t realistically maintain them.

- Comments Do Not Make Up for Bad Code! One of the more common motivations for writing comments is bad code. We write a module and we know it is confusing and disorganized. We know it’s a mess. So we say to ourselves, “Ooh, I’d better comment that!” No! You’d better clean it! Clear and expressive code with few comments is far superior to cluttered and complex code with lots of comments. Rather than spend your time writing the comments that explain the mess you’ve made, spend it cleaning that mess.

``` // Bad:

    // Check to see if the employee is eligible for full benefits
        if ((employee.flags & HOURLY_FLAG) &&
        (employee.age > 65))

    // Good:
    if (employee.isEligibleForFullBenefits())
```


Sometimes, comments are a justification. Sometimes you have to do things that seem like the wrong thing to when reading the code (like sending a POST request instead of a GET when a GET is clearly more appropriate, but you have to talk to a poorly-written API that will only respond to POSTs on that route). Comments help rationalize that decision for the next guy.

I also find TODO comments quite helpful. It requires far fewer brain cycles to process a TODO comment than to parse the code, figure out what it's doing, and make an assertion that it's incomplete.

Comments can also make code much more approachable to junior programmers, who may not have heard of principles like Tell Don't Ask, or Composition Over Inheritance. When I'm working with a junior dev, I find that comments usually reduce the number of interruptions I receive that are along the lines of, "Hey why did you do this thing this way?"

Really, it's just not a good idea to make sweeping generalizations like, "Comments are always failures". The real world has time and budget constraints, and comments are sometimes the most effective way to satisfy those without screwing the next developer to read the code.


If you're systematic about the syntax of your TODO comments, you can also 1) jump to them, 2) traverse them in order of priority, 3) automatically surface changes to the list of TODOs as comments in commit messages, and 4) use commit hooks to refuse to commit code with overly severe TODOs to certain branches.


I do 1) pretty frequently, and while I don't go so far as 4), I do use total TODO count as a heuristic from time to time.


Yeah, I've never got as far as 4. I do 1-3 on my main project at my day job.


> Programmers can’t realistically maintain them.

Why not? The effort involved is not very high.

If you mean that they won't maintain them, well, I agree. Sometimes I fail to do so myself - but that's my laziness, not because keeping a comment up to date is actually difficult. The fact that programmers can be lazy is why we put processes in place to catch ourselves - code reviews, code style enforcement, and so on.


> Why not? The effort involved is not very high.

Because, realistically developers will be lazy. For example:

"Sometimes I fail to do so myself - but that's my laziness"

> code reviews

So, here is the thing, "programmers can be lazy." Programmers can also miss things. Code reviews don't catch everything.

So, when someone says "programmers can’t realistically maintain them", they are being realistic. Really. It's great to be hopeful, but the simple fact is, you can't trust that comments are maintained.


Couldn't you use the exact same argument to say that it's realistically impossible to maintain a high quality, readable codebase, so why bother trying?

There's nothing that intensely difficult about implementing processes that keep at least the vast majority of comments up to date. If you don't feel like it, or your organisation doesn't have the will to enforce it, then fair enough. That's not the same as it being impossible.


I'll add comments to already existing bad code, describing the results of my archeology.

I should refactor. But sometimes it's not feasible when you're in a hurry and the area has no unit tests to prop it up. Adding a tag "TODO: CLEANME" or something similar works as a reminder.


This actually works even in natural language. If you think about it for a moment, sometimes what you thought isn't necessarily what you said, and most likely you will, either intentionally or unintentionally, resort to other means to communicate the thought, such as facial expressions, what you are wearing, and so on.

I think it's a common fallacy to believe that it is our failure when we can't express a particular thought. The language itself, be it human or the far more restrictive and qualitatively restrained computer version, is deficient in many regards.


It seems to me that the Haskell wiki's recommendations on commenting align pretty well with Uncle Bob's. Personally, I'm glad for this. On this topic, I agree with both Uncle Bob and the Haskell wiki.


I see rubbish like this in PHP (and Java) code all the time:

    /**
     * Frobnicates a foobar
     * 
     * @param Foobar $foobar The foobar to be frobnicated
     * @param int $intensity The intensity with which the foobar will
     *    be frobnicated (defaults to 4)
     * @return mixed The result of frobnicating a foobar
     */
    function foobar_frobnicate(Foobar $foobar, $intensity=5)
    {
        // frobnicates the foobar
        return $foobar->frobnicate($intensity);
    }
It's utterly ridiculous.

Pretty sure I've been guilty of this in the past, too. As I recall, the documentor tools make a lot of noise if you don't supply wasteful and irrelevant values for every single little thing even if it's blindingly obvious from the symbol, context or idiom what it means and what it does.


I like how you made the comment say 'defaults to 4' while the code says 5, this pretty much sums up my experience with 'documentation comments' as well.


Funny (and perhaps intentional) that your example comment and code disagree ("$intensity=5").


I think we can all agree that this is the most blatant example of useless documentation.


It's a bit contrived but it's not even as useless as it would appear to be (if you forget about the likely intentional mismatch between the default value and its documented value).

The purpose of this comment is obviously not to clarify the code for someone working on it, but to ensure the automatically generated API docs stay consistent. I write comments like these above functions all the time, because we have a zero-warning policy for doxygen comments over here, to prevent people forgetting to document public API methods (or slacking off out of laziness). Sure, the comment block is redundant since it contains nothing that cannot be derived from the parameter names and the name of the function, but it does make sure a doxygen run will not spew warnings and errors all over the place, drowning out uncommented methods with far less obvious functionality or parameters. The redundancy is a small price to pay to enforce a good self-documented API.

I really don't understand any of the discussions about not documenting code because it should be 'clean and obvious'. First of all that's mixing up 'how' and 'why' code is like it is, second it's a small effort to write and maintain code comments (contrary to what some people like to suggest otherwise), third it can help you organize your thoughts while you are writing the code (write the steps of your algorithm in comments, then translate them to code), etc.

Personally I also like how the syntax highlighting breaks up blocks of code with API doc comments, which makes it much easier to see where functions start and end when scrolling fast, or how they can separate distinct steps of an algorithm. 'No comments' really is the inverse of 'literate programming', like most of the time, the truth is probably somewhere in the middle.


Hmm. This is just one guy's style guide on the public wiki.

http://www.haskell.org/haskellwiki/index.php?title=Commentin...

It isn't official in any sense.


Right, also, it doesn't actually say avoid comments, it just gives examples of where it's best to try and find an alternative.

In the bitcoinj code style guide there is a big section on comments that gives positive examples as well as negative examples:

http://bitcoinj.github.io/coding-conventions


I've always treated comments as code smells. Not necessarily something bad, but something that at least suggests the possibility of suboptimal code.

One of the best cases for comments IMO is documenting an unexpected behaviour on the part of a third-party API. But even then, correct exception / error-handling code can obviate the need for comments in many cases.

If I'm reading code (from an experienced programmer) and I see a comment, I immediately pay attention, because Here Be Dragons.


The situation must be differentiated by language/environment. The suggestions for Haskell are certainly not bad. They hold, too, for many systems programming.

For scientific coding, comments should align with the underlying theory for the code: “This implements matrix transposition with regard to ... as defined by ...”, so that next generations can align code with papers better.

And when you’re in a wacky environment like the PHP runtime or coding for a moving target like the browser, comments might be indispensable to explain one or the other really strange way of doing things, where you simply have no other choice. Look at the [jQuery source code](https://github.com/jquery/jquery/tree/master/src), where they comment excessively, which browser quirk they address with which work-around.


> For scientific coding, comments should align with the underlying theory for the code

100x this. Scientific software should be held to a different set of standards than non-scientific software, primarily because you can probably not assume that your reading is familiar with the underlying domain.


> Scientific software should be held to a different set of standards than non-scientific software, primarily because you can probably not assume that your reading is familiar with the underlying domain.

As someone who works as a programmer and system analyst dealing with code in a non-scientific business domain where I've also worked on the domain side, I don't think that this separates scientific code from any other codes. Programmers often disdain domain knowledge beyond that which they already have found to be immediately relevant. Which is perfectly understandable -- there's a reason they chose to specialize in programming rather than as domain experts in whatever domain.


I thought through this some, and your comment resonates -- it's not right to set aside scientific code from other code with a complicated domain.

But I think complicated program segments related to business practices etc. also deserves comments, even just "see spec xyz" or "see section 1.2.3 of code xyz" (similar to how you might say "See Smith et al. '14" in a scientific setting)


One case of unexpected behavior which is best described in comments is when the simple and obvious solution to the problem is wrong, and has already been discarded.

(Preferably the reasons for discarding the simple solution should be provided as well, as circumstances may change.)


I often have to go commando scripting small tasks to deliver things within the week, and the only comments I couldn't live without are TODOs to mark things that are hacked together. If time is limited I'd always rather write cleaner code than more commented code.


Remember your gas mask if you ever check out literate programming...


Comments say what your code does, your code says how you do it. The swap example is trivial, but for most functions it is good to add an API comment, because how you use the function shouldn't depend on how it's implemented, but what it should do, described in the comment. That way you can change your implementation as long as you don't change the contract. In other words, changing how your code does something shouldn't therefore change what it does. And this last part is specified in the comment.


Well, this is Haskell we're talking about. Between the name, type signature and the fact that most functions are pure (so, no side-effects to describe), it's often obvious what they do.


Like

  (<+>) :: Monoid m => m -> m -> m
  (^?) :: s -> Getting (First a) s a -> Maybe a
As a Haskell beginner I didn't find it to be a particularly self-documenting language. Between the use of custom operators and point-free style you can write a lot of code without naming anything to give a hint about what you're doing.


So as another Haskell beginner, let me take a stab at the first one.

  * Return the first parameter
  * Return the second parameter
  * Perform param1 `mappend` param2
  * Perform param1 `mappend` param2
  * Return the mempty value for the Monoid m
The first two are unlikely to be correct, since if all they were doing was returning a particular parameter, then there is no reason to have the Monoid type constraint. The last one similarly makes no sense, since it's a function that is identical to `mempty` irrespective of it's parameters.

The order of operations however should be documented. I'm almost certain that the implementation is the third function, but a one line comment stating that could possibly be useful.

All of my above reasoning was predicated on an understanding of Monoids. So while I'm not sure the right thing to document is the function, I do think an explanation of `Monoids` should be documented in `Data.Monoid`.

PS - Where is that first function defined? I've used a similar operator defined in XMonad, but if I remember right that was defined over Arrows. Also is that second function from Data.Lens?


I assume line 4 was meant to be:

    * Perform param2 `mappend` param1
I'd be a little surprised if it was the third option, simply because that's already spelled <>. Hoogle doesn't turn up a definition with that signature, though.


Regarding the second, that sounds like lens. First of all, stay away from lens as a Haskell beginner :-P

But let's take a swing at it. We start with something of type (s). At the very end, we're left with something of type (Maybe a). Since we know nothing about the types (s) or (a), we need something to relate these to each other if the function is going to produce a (Maybe a) for us (unless it just always gives us Nothing).

There's a lot going on in that second argument, but we can clearly see that it's some type parameterized by (s) and (a), so it provides that connection. It "tells us how to get an (a) out of an (s) in a way that might fail" - which intuition is additionally helped along by the fact that the type so parameterized is called Getting.

There's a little more going on, and for that you'll need to dive into the (extensive) documentation for lens. One thing that is not going on is any side effects though. The operator section (^? foo) will take some (s) and turn it into some (Maybe a) based only on the information contained in that (s) and foo.


As another commenter said above, comments shouldn't say "what" your code does, but "why" you do it,... when you need an explanation. There's no better comment of what code does that code itself.


I think the saying is that comments explain why the code does something.


Here's a small function from a real world module used in a Haskell web backend. It decides whether a "work unit" is appropriate to pick from a queue. The first iteration was a pretty complex piece of code. When I refactor, I often think "this is unclear and should be commented," but I've learned instead to think "this is unclear and should be factored out and given a significant name." So I ended up with this:

    shouldPickWorkUnit :: (ImportId, WorkUnit) -> STM Bool
    shouldPickWorkUnit (k, u) =
      case hostNameFor url of
        Nothing       -> return True -- Invalid URLs are fast to process.
        Just hostName ->
          takeWorkThat'sAlreadyDone <*>
            (don'tTakeSomeoneElse'sWork <*>
              don'tExceedTheRateLimitFor hostName)
This way, the domain logic is legible from the actual code, which strikes me as almost always better than having tricky code with comments. Trying for this also encourages "domain-driven abstraction," and this is one of Haskell's greatest strengths.

In fact, the remaining comment can be factored away too:

    shouldPickWorkUnit :: (ImportId, WorkUnit) -> STM Bool
    shouldPickWorkUnit (k, u) =
      takeWorkWithInvalidUrl <*>
        (takeWorkThat'sAlreadyDone <*>
          (don'tTakeSomeoneElse'sWork <*>
            don'tExceedTheRateLimitFor hostName))
Advice like "avoid comments" needs to be taken as a calling for actually spending time and effort to write obvious code, and for using appropriate abstractions!


It's doesn't recommend avoiding comments - it encourages to write understandable code and avoid meaningless comments. It is a basic rule of the clean code.


The thing with comments is: You should add them for people that don't want to read your code line by line.

I don't want to run my internal compiler in my head when i'm reading your code, so you better make sure there's at least a docblock above every function that describes in 2 sentences what it does so I can get a global overview of what the heck this file is doing.

People that suggest that 'the code is the documentation' are always forgetting that reading code is way more taxing on the brain than reading english.


That is exactly why once should take the time to give meaningful names to their functions, classes, and methods. If you are having a difficult time doing it, your piece of code is probably doing too much. Split it into pieces that are more easy to name.


I already assume you are using meaningful names for functions, classes and methods, as any self-respecting programmer will do.

I can completely live with a 50 line function that does magic in a legacy project, as long as I don't have to read through it.

'split it into pieces' is everybody's favorite argument, but nobody is going to pay you to refactor it. DOCUMENT IT.


I've found there are several topics that even qualified, experienced, reasonable developers will always disagree on. dynamic vs static typing, YNGNI vs future proofing, IDE vs no IDE etc. Usually, a given developers opinion on these topics is informed by their specific experience and what has bitten them in the past.

Code comments definitely fall into this category. I've worked with developers who I greatly respect who are obsessive about code comments. I've even been told that the comments are more important than the code and in that specific context it made sense.

But my own experience and biases make me think code comments are a problem. I like to refer to them as future lies. There is virtually no back pressure on comments to keep them in sync with the code. There is no automated way to verify them and refactoring tools on comments are rudimentary at best. To put it simply, I no longer trust comments and will usually ignore them in order to verify the code itself. I can't count the number of times I've found comments that directly contradicted the code it was commenting. It isn't even uncommon to find comments that are incorrect when they are written!

As to the folks recommending comments that document the "why" of a piece of code, I'd counter that if you have a "why" you have a specification. If you have a specification it should be verified in a systematic way. So performance improvements, or specific client requirements should be encoded in tests so that they don't regress. Comments do not provide that safety.

That's not to say I never comment my code. Just that it always feels like a failure when I do. It is usually because it is cheaper to comment than to provide cleaner code or better verified specifications.


It seems like no one here shares my opinion on this: I really like comments, even if they just restate, in English, what the code does. I don't think that's pointless. There is big value in it. I can scan and mentally process English sentences much faster than code. With a heavily commented file you can just skim through the comments until you locate the part you need to work on (then slow down and read the code around it and edit it).

Look at the Backbone.js annotated source [1] (the stuff on the left is just the comments pulled out from the original source JS). The comments make it much, much quicker to grasp what's going on, even though many of them just state exactly what the corresponding code does, which according to the Haskell docs' advice is pointless and to be avoided.

[1] http://backbonejs.org/docs/backbone.html


> I repeat: Try hard - very hard - preferably repeatedly - to remove unexpected behaviour from your program. Comments can never fix unexpected behaviour.

This is golden!


I've seen this many times:

    ...thus they (comments) tend to diverge from actual implementation.
It happens, you update/refactor code, and forget to update the comments. Thus the comments are outdated or worse not applicable anymore. Common mistake by less-detailed oriented developers. Begs the question, in this case is is better to have confusing/incorrect comments, or no comments at all?


No comments are better than bad comments. There is nothing worse than a misleading description.


I've always gone with the adage: if the comment and code do not agree, don't assume that either of them are correct.

A bad description isn't just a problem in itself, it can indicate a worse problem sat waiting to jump out and bite as you walk by.


comments might diverge from behaviour but the code, almost by definition (modulo some crazy magic happening/broken interpreter ) _is_ the behaviour.


> code, almost by definition _is_ the behaviour.

Yes, but is it the intended and/or desired behaviour in all cases that the codepath in question will be expected to experience?

That is the problem, especially in code that deals with rare edge cases so is not run often, and/or covers many circumstances where it is right but is wrong for one set of inputs that no one thought to test before (or since that code last changes).


The best commenting system is a debugger stepping through the code. Unfortunately, I've yet to see a commenting style that is able to really document mental models about how the code works.


SEURAT is a research project that attempted this. I was a test subject for it a while back and found it pretty interesting. But its implementation at the time was an Eclipse plugin that probably hasn't been kept up todate. You can find a paper on it on the ACM digital library:

http://dl.acm.org/citation.cfm?id=1368215

I'm sure the dissertation is available somewhere on cs.wpi.edu, too.


" ...thus they (comments) tend to diverge from actual implementation."

In my experience comments are no more likely to diverge than tests are. With tests you have the advantage that they must compile. With comments you have the advantage that they are inline/interspersed with your code and so get read every time the code is read.

"It happens, you update/refactor code, and forget to update the comments."

So then the next developer to read that part of the code notices that the comment doesn't make sense, or is not well written, and they update it. No different than if they notice poorly named/misleading functions or variable names or a dozen other code smells. No big deal and certainly not a good case for commenting less.


"With comments you have the advantage that they are inline/interspersed with your code"

Just as a heads up, there are lots of testing paradigms that have the tests inline with the code it is testing. That they aren't the default in most languages is most disappointing.


I'm a big believer in function level comments in code, in a sort of doxygen-ish style (I write mostly C).

It allows you to document the intended inputs and outputs of the function and state its purpose. This increases maintainability and reusability.

Functions themselves should be short and written as a sequence of logical steps.

I'm also a big fan of doing things right rather than just hacking until it works, which seems to put me in a minority.


But the thing is, in C a geocoding function would probably receive two ints and return a string, while in Haskell you'd probably have a function of type "Location -> Address". The type system obviates much of the need for those comments.


Indeed, a solid type system would remove some of that need, in C it can be very important to document what precisely that pointer is pointing to. Is it a provided buffer, something allocated and returned? Multiple or single element? etc etc.

I'm guessing Haskell doesn't need that? A simple statement of purpose would still help though?


I also like to add doxygen headers to functions, but have stopped adding the inputs and outputs. Refactorings causes the doxygen to go out of sync with the code.

Currently I only do the following:

  /**@fn    foobar
   * @brief Does foo
   */
-edit formatting


This is true, if you're lazy!

In C at least, I think it's important to specify whether we're expecting a pointer to a single element, a pointer to an array, if the pointer is an output, etc etc. A uint8_t* could be many things...


Comments are lousy for describing what you are doing, but there are no alternative to comments for describing why something is done.


Similar thoughts were seen in the SICP book.

"In this book we don't use many comments; we try to make our programs self-documenting by using descriptive names."

http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html...


From the era when two poles were Lisp and C, I can sort of see that. In part because of the preference for longer identifier names in Lisp, versus cryptic abbreviations in C, some kinds of comments prevalent in C aren't as necessarily in Lisp. Instead of atoi() you'd have something like convert-ascii-to-integer.

In modern Lisp, though, it's still considered good form to include both a docstring, and internal comments explaining anything particularly tricky.


Note that this isn't the "official" Haskell style guide. We don't have one (although we probably shouldn't). This is one of the competing guides out there.


I'd say the language design and language ecosystem has a LOT to do with it as well. Here are a few lines of Java that I just had to write about 10 minutes ago.

  PendingResult<MessageApi.SendMessageResult> pending = Wearable.MessageApi.sendMessage(mGoogleApiClient, mWearableNode.getId(), path, data);
  pending.setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
      @Override
      public void onResult(MessageApi.SendMessageResult result) {
          ....
      }
  }
Okay, now suppose this were a Python-based API instead? Perhaps it could be something like this, after some relevant initialisation:

  wearable.sendmessage(mywearable, path, data)
  
  @wearable.onresult
  def onresult(result):
    ...
Tell me which one is more in need of commenting.


I totally agree with this. I like to put a bigger comment block at the top of my source files explaining the overall concepts and data structures used and then put few actual comments in the code. Instead I think about my variables and function names and make them talk for them-self. Commenting each and every element of your code will just make people (possibly yourself) curse at you when debugging your code and realizing that the comment was rendered obsolete 15 iterations prior and the code does something entirely different.


I generally sympathise with your sentiment - I think this jives fairly well with comments talking about 'why' rather that 'what'. I do favour function-level comments quite a bit for more complex functions.

That said, I think some of the commenters in this thread should spend time maintaining a MLOC+ sized code base before dismissing comments as 'code smell'. Even in well-written code, if you're a maintenance programmer who is unfamiliar with a particular functional area, a few comments talking about the overall purpose of the code and why it works the way it does can save you enormous amounts of time.

Finally, if people are letting comments go out of date, IMO they have a quality issue. Either the comments are useless and should be removed, or they're useful and should be kept up to date. If your developers are letting useful comment areas go out of date, it should get caught by code review.


Leo Brodie says in "Thinking Forth" in the style section: "The most-accurate, least-expensive documentation is self-documenting code". I am sure there are other prior examples.


I agree. Comments sometimes make it difficult to go through the source code. That's why I always loved Java naming convention that suggests variables and method names to be self-explanatory.


I currently write docblocks for everything I code.

It's crazy how much time I spend on them and sometimes they are confusing because the specs change and I keep forgetting to add/remove/update something in a docblock when I rewrite some part of the code it documents (I'd say between 10-20% of my commits are docblock updates).

I believe brief or even no documentation may be the best approach until you are on the verge of releasing a stable version.

While you are on developing and testing mode, it seems a better idea to forget about comments and focus on modularity.

After all, Why would I need comments if all the rest of my team sees is an interface satisfying a previously established and well defined contract? That's why docblocks should be only documenting public interfaces, some kind of dump taken from the part(s) of the contract they implement.

I'd consider instead other top priorites on those phases:

- Keeping an homogeneous codebase in regard of design and coding guidelines and conventions.

- Re-factoring before it becomes a problem

- Writing neat unit and integration tests

And, the most important:

- Keeping a channel open with the client, constantly feeding guided demos and prototypes showing your progress to make sure you are on the right track and you didn't get it backwards, updating specs and being realistic about what can be done and what not in which time frames with the provided resources.


> I've never seen a language's style guide recommend avoiding comments before

An official style guide? Maybe. But it is one of common philosophies. See for example:

"If you need to comment something to make it understandable it should probably be rewritten."

http://kotaku.com/5975610/the-exceptional-beauty-of-doom-3s-...


The stablished policy is: "don't use comments to replace proper names and abstractions".

I wrote more about this here (it's Lua code, but it applies to any language):

http://kiki.to/blog/2012/03/16/small-functions-are-good-for-...


This is not convincing to me because the examples are trivial:

    -- swap the elements of a pair
    swap :: (a,b) -> (b,a)
Yes this is redundant.

    let b=a+1   -- add one to 'a'
Yes this is also redundant

Does it mean that every piece of code can be expressed as clearly as in a one-line comment in natural language? I don't think so.


The argument is not to never use comments, but rather to avoid bad comments.


I realize this, but the article doesn't provide any clear definition of what actually is a bad comment. It only gives trivial examples of bad comments such as "increment a by one".

Since I don't think anyone here would argue that "increment a by one" is a useful comment, the part about duplicate/obvious comments isn't adding much to the discussion about the usefulness of comments.

Nevertheless, it's true that comments cannot be checked by the compiler, and that's a more interesting point, I think.


I have never seen comments like these except during arguments that good code doesn't need comments.


But you see, nobody on the internet has ever offered up examples of good comments before, at least that I can find. So if you say these comments are bad, but there exists good comments, why not provide examples of good comments to make your argument stronger?


What about the Code Complete examples posted somewhere on this thread? ("above", at the moment)?

What about checkable specifications together with a comment explaining the formula, particularly for anything with a nice physical intuition? This kind-of addresses the out-of-date comment problem.

Another example which came to mind is a Lamport comment about some sort of layout-related thing, I can't remember specifics. The comment gives a really good intuitive feel for why his code produces a nice-looking layout. Without the physical intuition provided by the comment, the code is pretty difficult to grok. I can't find it, so I really hope I'm not making this up...

edit: 2nd par


The article correctly advices against commenting the obvious. I think it is often practice by novice programmers to assure themselves about what the language expression actually does.

What the article omits is the suggestion of commenting the right way, i.e. adding reasoning or the description of the high level logic behind the code.


Yes, obviously the examples given in the link are bad style of comments. But sometimes you need to explain the reasons behind the (Haskell) equations, just like one would do in a Math paper. So there's a use case for the literate Haskell files *.lhs (http://www.haskell.org/haskellwiki/Literate_programming).


Code may explain what your code is doing, not necessarily why it is doing what it does in the way it does.

Comments may be a code smell when it is necessary to explain what your code is doing.

Anywhere where you have some freedom to solve a problem one way or the other it may clarify why the implemented approach was chosen.


Comment only magical code, but don't write magical code.


There are times when you absolutely want to comment something like an "Add" or "Swap" function.

eg.

// The reason we use a custom swap function instead of

// the one that is shipped with the framework is because

// of an edge-case that occurs quite frequently in our

// scenario

// Refer to Change Request 345.

void Swap (Foo a, Foo b) ....


I think you are missing the point there. Sure, I completely agree with you that those comments are crucial, but they are not informing about the code doing a swap, they are explaining the need of the applied workaround.


That's precisely the point. In most cases, what your code is doing should be obvious; the why, as others have stated, would be otherwise completely out-of-band information, which explains the necessity for comments.


Comments I liked to write were when I found successive optimizations (lots of symmetries in the algorithm) leading to very short code. Almost too factored to be understood easily so I added a comment wall above telling the steps I went through before hitting the final code below.


It is easy to spot (most of) the experienced coders from the newbie coders. Any programmer who has written his salt worth of code knows that comments can save your ass. Come back to some code ten years later and you can sit there staring at a bit of code no bigger than your thumb wondering what the hell it does and often it doesn't become clear until you shove some test samples down its interface and see the result. Whereas a simple comment is all it would have taken to clear it up from the start. People who argue that comments can get out of whack with code, well, of course they can, but that's no excuse. That's just a failure on the programmers part to always update comments when the code changes.


Personally I have no problems with comments in code for complex functions etc. But pointless comments like this below drives me insane.

// get the user $user = $this->getUser();

Times that by the thousands of lines in a project and you have one big headache!


> Personally I have no problems with comments in code for complex functions etc

I hope you have a problem with complex functions. (They should be made as simple as possible).


Heard this argument a few times and mostly I do agree, but in certain scenarios I'm not willing to spend a whole day on some perfect code when I can do it in a hour with some comments explaining it.

My scenarios for this typically include: * Disposable project, eg prototyping an idea for a client * I have an impossible deadline and I'm on a fixed project rate, maybe I should have quoted more, who knows, it happens


Why fear complexity when its the only way to get something done, other than not doing it?


There is no such complex function that can't be decomposed to bunch of simple(r) functions.


Often only with a deep understanding of the complex problem to understand its simplicity. But you have to ship in 4 weeks, so why not just get something working first?


> But you have to ship in 4 weeks, so why not just get something working first?

If you do that, after the deadline is over, you will get assigned another task with another 4-week deadline. And then another. The code will get increasingly complex until you can't keep with it any more. And then you will leave the company, or they will fire you. And the people who gave you that deadline will refer to you as "the guy who left that horrible mess of code".

I decided long ago that that's not how I want to live my life.

If someone gives me an unreasonable deadline, I negotiate it. Hard. By explaining the problems, and making sure everyone understands the tradeoffs being made.

And if the deadline is really immovable, I negotiate a period to refactor after the deadline is passed, and in which I am not assigned other tasks.

And if that is not possible, then I start looking for another job. Fortunately now it's a great time to be a programmer.

But hey, if that works for you, then great. To each his own.


> But you have to ship in 4 weeks, so why not just get something working first?

Of course, this sometimes happens, but it shouldn't be encouraged. This way you are creating technical debt, which will be very expensive to pay off.


I actually work on problems that haven't been solved previously (or why not just get a dev to do it rather than a researcher). I get offended when some dev who writes web apps connecting to databases all the time says "all code should be simple." They really don't have a clue.


At what point is simple simple enough? You can simplify for a long time just by working at the same problem for a few years. But wow...not everything is a basic crud app.


> At what point is simple simple enough?

It's hard to explain. You know it by experience.


Because simpler code usually leads to less bugs, which is faster and cheaper than complex, buggy code.


I find that the better I understand a problem, the simpler code I can solve with it. But I can also understand the problem better by solving it with code, and repeat a few times for a few months to approach an ideal solution.

Writing simpler code is more expensive than writing complicated code for that reason, unless you are a genius who can simplify any complex problem instantaneously. Anyways, your argument basically amounts to "do good, no do bad."


It's often a good idea to comment "why" the code exist, if it is non-obvious (e.g. it's obvious to sanitize input parameters). The comment must be short and possibly point to a ticket wrote somewhere else.

It may be a good idea to comment "what" the code does, if it isn't clear (the code itself is "how" it is done, but "what" does it do may be hard to read, e.g. sometimes you use a clever hack for performance reasons).

As always, handle with care :-)


I was always told that if someone couldn't tell what your code was doing by glancing at it, you'd done it wrong and should re-write it.

I know that's absurd in practice, we don't always have the time but I've always used comments as a last resort.

If I need to comment code to make it understandable at a glance, so be it but I'd rather avoid them all together and rewrite until it's clear enough without them.


I disagree with that sentiment.

Using Python or Perl it is easy to go from a for loop to a map or list comprehension. For many less experienced programmers it will make it less readable and more difficult to comprehend. Using a more functional approach will usually lead to less side effects and silly bugs, so I prefer to code this way, and add a comment to explain what the line is doing if it is not obvious.


I want comments to give me a short-cut to reading a long block of code, and I want comments to give me a basic method of analyzing the code for correctness. The thumb-rule of documenting "why" rather than "how" seems to apply.

I shouldn't have to read code in detail to understand it, unless it is broken and I am fixing it. Comments should inform me on the broad strokes of the code.


Write comments that explain why a certain line is there.

Let's say you are parsing a standard tab delimited file. You find that the tab delimited file has some non-standard features, so you have to write some extra lines of code to handle it. For people who thinks the code just parses a standard tab delimited file, these lines will be confusing, so you comment these lines and say why you included them.


Or create a function to handle that case, name it appropriately, and call it. Thus, no comment is required. You can also test the additional method in isolation, if you wish.

I appreciate that this type of thing is language dependent.


This style guide is NOT against comments. It is just stating the obvious best practices which have always been around for all languages ...


This submission needs to have a different title. It's not very clear whether the submitter is being genuinely surprised or sarcastic.


I would say, never assume sarcasm is in play unless it's absolutely clear. So I think this title is fine.

If the OP meant to be sarcastic, that's just like me saying "yes" when I mean "no"---my mistake, not yours, and you can't be blamed for assuming I meant what I said.


This style guide DOES recommend avoiding unnecessary comments and is an easy one to understand and remember. Good start for all novice coders. https://google-styleguide.googlecode.com/svn/trunk/shell.xml


Linkbait title. Rolls eyes yet again.


Martin Fowler's Refactoring says that, possibly paraphrasing here, most comments are bugs.

I do favor putting a short comment on some methods/functions/procedures.


Articles about writing code without commenting sound like articles about driving your car without using the brakes: theoretically possible, but impractical.


Its quite common in coding communities and style guides.


Comments aren't necessary at all. If the code was difficult to write, it should be difficult to read. :-P


Read the linked page. This one doesn't either. It says to prefer fixing bugs over documenting them.


To rephrase - code makes comments understandable?


The article is spot on. Comment as last resort.


Good code should be self documenting.


> Good code should be self documenting.

Good code needs no test either,... wait no ,that's a stupid thing to say,because nobody writes "good code",code isnt good or bad,it either results in the expected behavior or not.


Depends on how you define "expected behavior".

If it means "the machine executes it and is able to produce the expected outputs with the right inputs", and nothing else, then you are missing a key concept about code.

You see, code is not written for machines. If that was the only reason, we would all write direct binary. Code is written for people. More specifically, other people. (Or you, in the future).

If no one (except a machine) is capable of understanding a piece of code, then that code is indeed bad; it has failed its main purpose. The more understandable by people code is, the better it is.

I agree that once compiled/interpreted, these differences don't matter. Until the next bug or feature request arrives. Then it matters quite a lot.


You want a good rule: Write More Comments! Comments are documentation and few programs are ever documented enough.


how about a language that has no support for comments!?


A partial list of problems

Assume someone who can't write clear code can write clear comments. Also search and replace clear with "readable" "literate" "concise" and last but not least, "correct"

Assume a programmer has full authority over all 3rd party, supplier and customer APIs, interdepartmental processes, and all business logic, management selected fad technologies, such that its logically impossible to be unable to always factor out weird confusing stuff resulting in clear code / clear comments. My program is the world and none have dominion over any of the rest of it and any other conception of reality is wrong. (And edited to add I've gotten involved in some weird "EE" stuff and like it or not, the world itself is plain old weird and illogical sometimes and if you don't like that, a computer programmer can't fix it, only a physicist, or maybe a diety. This isn't a big problem in the world of CRUD apps but it does happen)

Assume comments only exist as a inspirational descriptional prose tool. Sometimes I use them as placeholders for something I know belongs there but either I or the business are not ready. Sometimes I use them as a cheatsheet because I'm personally really uncomfortable. Sometimes I use them as an outline more like names on a map to orient myself than a travelogue.

Assume all programmers fit the management ideal of identical replacable cogs. "How could someone work here without knowing by heart how to convert dBmW into volts or the difference between S21 and S12 microwave scattering parameters, so I have no need to comment this, but I've never actually used this corner of matrix math while employed before so I'll make one of those laughable comments that is a simple linear translation just to help me keep my head on straight.

Assume comments go thru the same code review process as code. If a comment in file A tangentially relates to function Q in file B, and you modify function Q, your code review process will probably examine file B and the comments in it, but how do you ensure file A gets modified? This is especially bad with those "because" style comments. (edited to add, at least date your comments?)

Assume no metrics exist WRT comments to be gamed. Your continued employment and possible promotion exist because of a content free meaningless metric number, perhaps lines of comments. Ask a professional to generate a number, you'll get a nice number, but unprofessional work. Ask a professional to do professional work, and you get professional results and who cares what the number is. That requires a high caliber of management, usually unavailable. Even worse a low caliber of management, the kind most likely to demand adherence to meaningless metrics, is also exactly the type least likely to successfully evaluate the professionalism of the code so they don't end up with good code. So you get meaningless metrics resulting in meaningless comments right next to bad code, if you enforce metrics.

Assume there exists a silver bullet for comments, just like this months silver bullet fad for code also fixes all problems.

(edited to add) Assume there's one human language. I worked at a place where outsourcing and H1B took complete control over corporate IT such that code comments and even some internal documents were no longer written in English. This makes comments rather hard to follow when engineering tries to cooperate with IT. So... I'd love to follow your detailed internal process for dynamic DNS for my spectrum analyzer, but you guys don't use English and we don't use your India language, so...


I disagree. You don't need to comment simple and universal concepts like this:

    swap :: (a, b) -> (b, a)
    swap (x, y) = (y, x)
or even this:

    map :: (a -> b) -> [a] -> [b]
    map f [] = []
    map f (x:xs) = (f x):(map f xs)
Those functions actually are self-documenting. Trying to explain them further is just going to clutter the page.

On the other hand, at 10,000 lines of code, a lot of that being parochial business logic, I'm going to want high-level documentation of why all this code exists. My emotional impulse is going to be to throw out all this shit code (in the business world, all code is shit) so please tell me why that is a bad idea. (I know it is, and I'm not going to do it, but please tell me why I'm not going to do it.) I'm going to want an entry point. I can't count the number of days of life I've lost just looking for entry-points in gigantic enterprise codeballs. Like, what actually runs?

Actually, 10,000-line single-programs should be rare-- Big Software is almost always a mistake, see here: http://michaelochurch.wordpress.com/2012/04/13/java-shop-pol... but that's another rant.


There's similar advice in the Ruby Style Guide - https://github.com/bbatsov/ruby-style-guide#no-comments

Comments often go out-of-sync with the code, so I think it makes a lot of sense to prefer writing comprehensible code instead of trying to explain with comments something totally incomprehensible.


It's weird to me how people will slate low quality code, but think it's okay (or inevitable) to let comments go out of date. If your comments aren't useful, delete them. If they are, keep them up to date. It's part of behaving responsibly towards the rest of your team just as much as writing readable code is.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: