15 ms·
I've never seen a language's style guide recommend avoiding comments before
- duncan_bayne 12y agoI'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.
- Boldewyn 12y agoThe 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 https://github.com/jquery/jquery/tree/master/src), where they comment excessively, which browser quirk they address with which work-around.
- nmrm 12y ago> 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.
- dragonwriter 12y ago> 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.
- nmrm 12y agoI 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)
- krfsm 12y agoOne 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.)
- FranOntanaya 12y agoI 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.
- dscrd 12y agoRemember your gas mask if you ever check out literate programming...
- kevinpaladin 12y agoI 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.
- krat0sprakhar 12y ago> I repeat: Try hard - very hard - preferably repeatedly - to remove unexpected behaviour from your program. Comments can never fix unexpected behaviour. This is golden!
- samuli 12y agoThe 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.
- timnic 12y agoYes, 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 http://www.haskell.org/haskellwiki/Literate_programming).
- vince_refiti 12y agoComment only magical code, but don't write magical code.
- deleted 12y ago[deleted]
- Myrmornis 12y agoThe article is spot on. Comment as last resort.
- MerreM 12y agoI 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.
- collyw 12y agoI 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.
- spacemanmatt 12y agoI 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.
- skriticos2 12y agoI 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.
- AlisdairO 12y agoI 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.
- tomp 12y agoThis submission needs to have a different title. It's not very clear whether the submitter is being genuinely surprised or sarcastic.
- javert 12y agoI 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.
- bnegreve 12y agoThis 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.
- lawn 12y agoThe argument is not to never use comments, but rather to avoid bad comments.
- bnegreve 12y agoI 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.
- seanmcdirmid 12y agoBut 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?
- nmrm 12y agoWhat 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
- viach 12y agoTo rephrase - code makes comments understandable?
- koonsolo 12y agoComments 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.
- icebraining 12y agoWell, 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.
- tveita 12y agoLike (<+>) :: 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.
- vamega 12y agoSo 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?
- josch 12y agoLeo 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.
- Nursie 12y agoI'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.
- kabouseng 12y agoI 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
- Nursie 12y agoThis 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...
- icebraining 12y agoBut 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.
- Nursie 12y agoIndeed, 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?
- tibbe 12y agoNote 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.
- bozhidar 12y agoThere's similar advice in the Ruby Style Guide - https://github.com/bbatsov/ruby-style-guide#no-comments 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.
- AlisdairO 12y agoIt'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.
- yxhuvud 12y agoComments are lousy for describing what you are doing, but there are no alternative to comments for describing why something is done.
- blowski 12y agoAvoiding 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.
- augustl 12y agoCompletely 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".
- couchand 12y agoin 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.
- josephlord 12y agoPutting 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.
- krzrak 12y agoIt'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.
- warrenmiller 12y agoGood code should be self documenting.
- aikah 12y ago> 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.
- otikik 12y agoDepends 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.
- nodesocket 12y agoI'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?
- seanmcdirmid 12y agoNo comments are better than bad comments. There is nothing worse than a misleading description.
- dspillett 12y agoI'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.
- rtpg 12y agocomments might diverge from behaviour but the code, almost by definition (modulo some crazy magic happening/broken interpreter ) _is_ the behaviour.
- seanmcdirmid 12y agoThe 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.
- nirvdrum 12y agoSEURAT 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 http://dl.acm.org/citation.cfm?id=1368215 I'm sure the dissertation is available somewhere on cs.wpi.edu, too.
- riquito 12y agoIt'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 :-)
- nrzuk 12y agoPersonally 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!
- otikik 12y ago> 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).
- deleted 12y ago[deleted]
- seanmcdirmid 12y agoWhy fear complexity when its the only way to get something done, other than not doing it?
- krzrak 12y agoThere is no such complex function that can't be decomposed to bunch of simple(r) functions.
- seanmcdirmid 12y agoOften 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?
- notduncansmith 12y agoBecause simpler code usually leads to less bugs, which is faster and cheaper than complex, buggy code.
- daemonk 12y agoWrite 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.
- auxbuss 12y agoOr 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.
- igitur 12y agoComments aren't necessary at all. If the code was difficult to write, it should be difficult to read. :-P
- otikik 12y agoThe 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-the-universe/ http://kiki.to/blog/2012/03/16/small-functions-are-good-for-...
- dons 12y agoHmm. This is just one guy's style guide on the public wiki. http://www.haskell.org/haskellwiki/index.php?title=Commenting&action=history http://www.haskell.org/haskellwiki/index.php?title=Commentin... It isn't official in any sense.
- mike_hearn 12y agoRight, 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 http://bitcoinj.github.io/coding-conventions
- chiachun 12y agoSimilar 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#footnote_Temp_197 http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html...
- _delirium 12y agoFrom 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.
- denizozger 12y agoRobert 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()) ```
- notduncansmith 12y agoSometimes, 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.
- LeicaLatte 12y agoIts quite common in coding communities and style guides.
- deleted 12y ago[deleted]
- rotten 12y agoOf 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.
- seanmcdirmid 12y ago> 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.
- anthracis417 12y agoForgive 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.
- agumonkey 12y agoComments 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.
- transfire 12y agoYou want a good rule: Write More Comments! Comments are documentation and few programs are ever documented enough.
- GazNewt 12y agoLinkbait title. Rolls eyes yet again.
- jabbrwcky 12y agoCode 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.
- ilitirit 12y agoThere 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) ....
- ricardolopes 12y agoI 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.
- notduncansmith 12y agoThat'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.
- stared 12y ago> 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-source-code http://kotaku.com/5975610/the-exceptional-beauty-of-doom-3s-...
- michaelochurch 12y agoI 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-politics/-- http://michaelochurch.wordpress.com/2012/04/13/java-shop-pol... but that's another rant.
- SchizoDuckie 12y agoThe 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.
- ARussell 12y agoThat 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.
- SchizoDuckie 12y agoI 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.
- mbrock 12y agoHere'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!
- dheera 12y agoI'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.
- shabbyrobe 12y agoI 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.
- SchizoDuckie 12y agoI think we can all agree that this is the most blatant example of useless documentation.
- w0utert 12y agoIt'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.
- VLM 12y agoA 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...
- bnelissen 12y agoThis 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 https://google-styleguide.googlecode.com/svn/trunk/shell.xml
- kasey_junk 12y agoI'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.
- gaelow 12y agoI 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.
- deleted 12y ago[deleted]
- vs2 12y agohow about a language that has no support for comments!?
- kelvin0 12y agoThis style guide is NOT against comments. It is just stating the obvious best practices which have always been around for all languages ...
- transfire 12y agoIt 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.
- callum85 12y agoIt 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 http://backbonejs.org/docs/backbone.html
- judk 12y agoRead the linked page. This one doesn't either. It says to prefer fixing bugs over documenting them.
- scott_karana 12y agoArticles about writing code without commenting sound like articles about driving your car without using the brakes: theoretically possible, but impractical.
- wglb 12y agoMartin Fowler's Refactoring says that, possibly paraphrasing here, most comments are bugs. I do favor putting a short comment on some methods/functions/procedures.