15 ms·
I worked with some Rails folks a while back who were utterly convinced that comments were to be avoided because it meant your code was not clear. I agree that
by davidw 4y ago
I worked with some Rails folks a while back who were utterly convinced that comments were to be avoided because it meant your code was not clear.
I agree that comments explaining 'what' is happening are mostly useless. Write clearer code. But 'why' comments are good. Most things can be coded up different ways. Tell me why you chose this way. Tell me about constraints that might not be immediately obvious. Let me know if indeed, it could be cleaner, but you were in a hurry (this is a thing that happens in the real world), or if it's that way for a specific reason.
- JohnBooty 4y agoI worked with some Rails folks a while back who were utterly convinced that comments were to be avoided because it meant your code was not clear. One of the few things that makes me want to reach a management position is my burning desire to alter this widespread, toxic, and absolutely bizarre belief. As an IC, even a senior IC, it's difficult to effect this change.
- paulddraper 4y agoWhat question will the next engineer have about your choice? 1. Rewrite your code to make the answer obvious. 2. If that's not possible use a comment.
- layer8 4y ago3. Be aware that programmers tend to be bad at judging what is “obvious” about their code.
- kawsper 4y agoArkency, a very well-known Ruby consulting company (at least in Europe), are the ones I've seen shout about this 'rule' the loudest: https://twitter.com/arkency/status/1254784379190038534 https://twitter.com/arkency/status/1254784379190038534
- latchkey 4y agoMy time at Pivotal Labs was similar. "The tests are the documentation!"
- Yoric 4y agoI have worked with a few developers who shared this motto. I didn't agree with them. While it's anecdotal, my understanding is that we were simply working on very, very different codebases. I was refactoring multi-million lines C++ codebases, implementing concurrent algorithms in which dependencies cannot be expressed through language constructs and I had to make non-trivial choices to prioritize performance, or safety, or security at the expense of readability. On the other hand, these (few) developers were working on writing fresh code, with less footgunny languages, with simpler data and control dependencies and didn't need to make hard choices due to perf/safety/security.
- twobitshifter 4y agoI’ve surprisingly heard it said on a c++ project.
- Yoric 4y agoThat's... surprising indeed! What kind of domain was it?
- twobitshifter 4y agoSimulation
- vkou 4y agoOh? Their tests have 100% coverage of every feature, and every meaningful, non-obvious interaction between features?
- latchkey 4y ago
- latchkey 4y agoDocument the why, not the what.
- collyw 4y agoA lot of code is WTF enough that a comment explaining what it is attempting to do might be helpful. The real world is full of absolutely shit code, but it still earns the company money.
- latchkey 4y agoHmm... I think you might be missing the concept a bit. What I mean is that there is a lot of documentation that is like this: /* The phone number */ private static String phoneNumber; That is considered 'the what', the documentation doesn't explain 'why' the phone number is a field on the class. This might be obvious because the class is called 'Address'... so people will argue that it is self documenting, and it is. The WTF code is 'the why'...
- deathanatos 4y agoIn something like your example, the what is obvious. But I've seen a lot of code where the what is not at all obvious, and a comment succinctly summing or breaking it down up would help drive the understanding. The way is useful in addition to that, and often IME far more important than the what. IMO you should document both, as necessary, and that's the hard part/skill. You have to treat it like you won't remember it in 6 months, because in 6 months, you won't. A lot of devs don't do that. (A fair number of devs won't follow the style guide / idiomatic patterns of a language if there isn't a CI check forcing them to, and will argue to all ends with a human as to why it ought not apply to them, to the great detriment of their code's readability to other experience practitioners of the language. Oddly CI enforcement usually works better, why I don't know.)
- latchkey 4y ago> I've seen a lot of code where the what is not at all obvious So then the question that needs answering is: "why" is the what not obvious? Document the "why."
- corytheboyd 4y agoHaving worked with Rails folk for many years, they do have some weird strong opinions, this being one. The argument that comments shouldn't be made because they'll "become stale" is pretty lame IMO. It's either not a big deal or the end of the fucking world for some reason lol. Maintaining code is just... work. You just do it. That includes comments.
- mgkimsal 4y ago> The argument that comments shouldn't be made because they'll "become stale" is pretty lame IMO Better not write tests either, because those will become stale too. And any sort of user documentation/support/etc. It'll all just become stale. It's almost as if code is just part of a larger 'thing' that has to be maintained.
- tcgv 4y ago> Better not write tests either, because those will become stale too Unit tests are easier to maintain when incorporated to a CI/CD pipeline. Then every pushed commit (or Merge Request) will trigger the test suite to run and in case one of the tests fails the team will know.
- p1necone 4y ago(well written) tests tend to fail (or fail to compile) if they're 'stale' though, so they force you to maintain them just like other code. (I'm not arguing against writing comments though - the 'they'll get stale' thing is not enough to make them not valuable)
- hbrn 4y agoI don't see a difference. If you write good tests and use a tool (CI) that detects them going stale, tests will never be stale. If you write good comments and use a tool (code review) that detects them going stale, comments will never be stale. In order for tests to not get stale, you need perfect (well written) tests. In order for comments to not get stale, you need perfect code reviews. Neither of those exist in real world: code reviews are done by humans, tests are written by humans.
- randomdata 4y ago> I worked with some Rails folks a while back who were utterly convinced that comments were to be avoided because it meant your code was not clear. What this means is that if your Ruby code is clear it should read like natural language. Injecting subtitles into the middle of the expression # I decided to phrase it this way because I was in a rush and it was the first thing that came out. With more time I could no doubt articulate this in a more communicative way, but for the sake of a random post on the internet I'm not terribly worried. interrupts the flow when one is reading the code, which makes for a much less pleasant experience. Ruby may not be the only language that is like this, but it is relatively unique in this regard. Comments in other languages don't seem to cause the same interruption. # That's all I've got. Time to clean up. I'm not sure this means don't provide additional information to future readers that may be beneficial, but be discriminating in where you put it. Or do whatever you want. Who cares what someone else thinks?
- davidw 4y ago> should read like natural language The history of programming is full of that notion and it never really works out. See: COBOL, SQL, and so on. I think we can all agree that code that is easy to read is better, but sometimes the 'why' needs spelling out.
- randomdata 4y agoTotally agree. I even said so at the end. You would have noticed if the comments didn't get in the way. :)
- rubyist5eva 4y agoAs a "rails folk", we aren't all like that :)
- citrin_ru 4y agoMany people think their code is clear. The problem is it is clear often only for the author and sometimes for a limited time even for the author. If anyone else start to working with the code questions usually arise. And you can prepare comments for at least some of such questions. In my practice I often see code where useful comments are missing and hours of research required to learn something author for sure knew. Code which has too much comments to me is an imaginary problem - I've seen it at most a couple times in my career and one of them was the code written by a junior developer in a style one can expect in a tutorial or a book. But usually people quickly learn to not add unnecessary comments (and eventually start adding too little of them).
- weatherlight 4y agoMany people think their subjective comments are clear! Code doesn't lie, comments do.
- MrGilbert 4y agoYet, code might not tell the whole story. It's a pitty.
- afandian 4y agoI wouldn’t use the word ‘lie’ but plenty of Rails code I’ve seen has mystery effects and hard to follow coupling due to monkey patching and the like. Comments please.
- lordgroff 4y agoSo train people to write better comments, because although code doesn't lie (questionable as that is since the intent behind the code and what it does doesn't always align) it can be literally the worst implantation of an algorithm imaginable, and so we teach people how to code. Teaching people how to comment is a skill that's just as important and nothing turns me off a project faster than the "code is its own documentation" mantra.
- afarrell 4y ago
- weatherlight 4y agoIf this study is to be believed. Citation-> https://cacm.acm.org/magazines/2017/10/221326-a-large-scale-study-of-programming-languages-and-code-quality-in-github/fulltext https://cacm.acm.org/magazines/2017/10/221326-a-large-scale-... The 5 programming languages with the least amount of bugs are: Haskell Ada Scala Rust *Drum roll please* Ruby Ruby is nothing like the other languages above in design, but that community has fantastic conventions around code clarity, code quality, testing, continuous integration, etc. Comments are for things like, `Todos`, Noting a specific algorithm, maybe a link to a white paper, noting a violation of a convention for speed, security, or some other performance reason. Comments are for things that are __impossible__ to tell from the code.
- otikik 4y agoAgree with most of what you said, except on the __impossible__ part. You can tell everything with code, given enough time and resources. Nothing is "impossible". But there's a point where you hit diminishing returns. It's about efficiency. Other devs, or your future self, will have to time trying to build the same "castle in your head" as you did. Can a comment shorten that time? If a one-line comment saves 15 minutes of investigation in aggregate, that's a no-brainer. You should add it. Conversely, a line that says "add 5 to x" is just wasting everyone's time. As a general rule, once I have finally understood a particularly hairy piece of code, I don't want to do it again in 6 months. I have even done ASCII diagrams in the comments explaining how a particularly hairy piece of code worked, when I hated it enough.
- jofer 4y agoASCII diagram comments are surprisingly common in scientific computing, FWIW. It's not so much that it's always hairy code, more that it helps to add some visualizations of what's going on. Math vs intuitive understanding are often very different things. It's something I wish was more common than it is. Sometimes you really want that ASCII pseudo graph explaining how minimizing this thing relates to that other thing that we actually care about. Taken a step further, I really wish we had better systems for managing this type of information alongside a codebase. E.g. the whitepaper, or presentation, or figures, or whatever is often very necessary to understand the code, and ideally it would be under version control and live neatly alongside things. Nicely rendered docs definitely help with this (e.g. latex in comments), but I'm always surprised there aren't more people focusing on this aspect of information management.
- claytonjy 4y agoI worked at a late-stage Rails-based startup that had "dont write comments" as an engineering principle! The python folks before me used this to avoid writing docstrings for modules/classes/methods, so code could only be understood by reading the entirety of it. Throw in some deep class hierarchies and it was very hard to onboard there.
- makeitdouble 4y agoTBF, deep class hierarchies will hard to onboard whatever you do. If you're relying on comments to help with that, you'll have to share the same mindset as the person writing the comments, except there's probably multiple years of understanding gap between you and them.
- ed-209 4y agoSmall, well named functions have served me well in this regard, eg. if (theWhy()){ theWhat() }
- davidw 4y agoSounds good in theory. In practice, you get stuff like https://github.com/git/git/blob/master/cache-tree.c#L246 https://github.com/git/git/blob/master/cache-tree.c#L246
- machiaweliczny 4y agoThis is something many people don’t do. They just put some weird statements that will change with time and deciphering what they meant is pain
- adamwk 4y agoI went from a rails developer to iOS; Apple and iOS developers in general are pretty good at comments, and I now value them more. Comments at the API level mean I don’t have to go diving however deep to find out what a method does. If they’re really good, they can also be used to distinguish the specification from what’s actually happening when there are bugs. In the simplest cases, sure you don’t need to write “getName returns a user’s first name and last name separated by a space character,” but I’m guessing the method requestPurchase will have a lot of nuance and I hope it’s documented (yes, even the “what happens”)
- still_grokking 4y ago> “getName returns a user’s first name and last name separated by a space character,” This would be actually a quite interesting comment as it indicates that the implementation of `getName` is buggy in regard to internalization. Here's the classic post about this topic: https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/ https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-...
- mbesto 4y agoThe best comments I've seen go something like this: # this is going to loop 4x and call foo_bar on the 4th time because when you calculate this number it needs the 4th time to calculate the difference from the sales tax. weird, I know, but the business has special rules about how taxes work in California
- q7xvh97o2pDhNrh 4y agoShed a tear for how little our industry values conciseness, and then consider: # Call foo_bar only on the 4th loop iteration to handle the weirdness of calculating taxes for California. (I've just joined a company where everyone's constantly writing giant docs, and no one seems to grok the idea of a "living doc" that gets edited and refined. I think it's slowly making me allergic to verbosity.)
- mbesto 4y agoI get your point (yours is written much better), but having comments that feel more like inner monologue is actually a good thing.
- billforsternz 4y agoThese are both terrible comments (IMHO) because they tantalise the reader (the coder knew why they did this mysterious thing!) but don't actually really explain why this is necessary or how this mysterious thing actually addresses the messy reality involved. The problem might just be that it's an unrealistic example.
- gymbeaux 4y agoI tend to be the one who comments code the most on my team. I’ve learned how often and what to comment via my side projects. I tend to stop and go with them, sometimes going a year or two before picking them back up again. You figure out what you wish you’d left yourself as comments.
- gregmac 4y agoI'm at the point where I want to see docs on any non-private properties/fields, methods, parameters, classes, etc. I think there's nearly always value to be added: * Explaining required fields, if null/blank/0 is allowed, where an ID comes from (db vs app-generated), if string values are formatted or require formatting (credit card, phone numbers), max length or other restrictions * If a class/method is thread-safe or not (when not obvious and misuse is dangerous), error conditions, timeouts. * Any external or indirect dependencies for use (config, packages, etc) * Links to other docs/wikis or tickets is hugely useful. When you're writing/working on the code you already know all this stuff, and it takes only a couple minutes to document. When someone else (or you, 6 months later) comes along to use or modify it, figuring everything out from scratch can take hours -- or worse, bug reports from QA or customers. Docs shave this down to seconds and directly avoid bugs. The other huge benefit I often experience is through trying to write docs for something I realize there's a better, more obvious name that makes it easier to use and requires less explanation (less docs). This happens on easily 5-10% of the things I write docs for.
- somenameforme 4y agoI always find the 'self documenting code' concept to be a bit misleading. Because intuitively the idea is that you'd be able to read the actual code and understand what it does, without having to rely on potentially dated or otherwise invalid comments. But in reality we're not really talking about code, but about things like function names - which suffer all of the potential woes as comments, even if to a lesser degree in practice. For instance, this [1] is a clean implementation of quicksort, which I offer as an example of any non-trivial algorithm. You can't really write it in a way that would make the idea clear to anybody who wasn't already familiar with the algorithm, because the idea itself is non-trivial. So the way intent is made clear and documented is by making sure the function is called QuickSort. And that is indeed 'self documenting', but really in a way that has nothing to do with the code itself. [1] - https://www.w3resource.com/csharp-exercises/searching-and-sorting-algorithm/searching-and-sorting-algorithm-exercise-9.php https://www.w3resource.com/csharp-exercises/searching-and-so...
- sam0x17 4y agoRails guy turned rustacean here. If I have a piece of code that looks gnarly, I'll write a comment above it explaining what it does. Elegance != readability always. This can often happen with complicated map/filter/etc chains (both in ruby and in rust!) that are compact but are complicated enough that your eyes glaze over when you read them. Anything eye-glaze-over-ey is probably worth a comment in my opinion. Other times to comment include when there is some sort of dirty hack, TODO annotations, etc.
- tigershark 4y agoThe why should be clearly explained in the Jira ticket associated with the commit. Comments are useful only to explain non obvious corner cases and invariant. You can write whatever you want in your Jira instead of polluting the code for everyone.
- esskay 4y agoThere were similar discussions in the PHP community, with arguments that were sensible and rather stupid on both sides of the argument. I'm honestly a bit torn by it. Yes, your code absolutely should be written in a way that keeps it tidy and easy to understand. But you've always got complex situations which arent always going to be easy or obvious for someone fresh to the codebase. There should be a good middle ground. I dont need to see comments saying "this is a loop that gets all the users". If its got a variables called users, calling a methog called "getUsers()" then thats pretty damn obvious whats happening. However if you then go on to do something weird like loop over each user and calculate a score based on the number of posts they've made then theres undoubtedly going to be some logic in there that even just a simple one sentence comment will help someone understand. It's a fine line, and getting it right is a skill in itself.
- davidw 4y agoRight, it's about the "why". For instance with your loop that calculates a score, I might want to know why it wasn't done in SQL. Or if it could be, but whoever was writing it just wanted to hurry along. Is there a TODO to get rid of an N+1 problem associated with it?
- watwut 4y ago> I worked with some Rails folks a while back who were utterly convinced that comments were to be avoided because it meant your code was not clear. Obviously, unclear code without comments is better then unclear code with comments.