7 ms·
> Prefer code to comments I used to make this same argument, and then took it overboard by never commenting. After reading some literate codebases, I’ve change
by christophilus 8y ago
> Prefer code to comments
I used to make this same argument, and then took it overboard by never commenting. After reading some literate codebases, I’ve changed my mind.
Code is (almost?) always obvious to you as you are writing it. So, you never recognize code that is in need of a comment until you come back to it and struggle to understand its purpose and the context that gave it birth.
I now follow a rule: a meaningful comment at the top of each file. A comment on every exported function / value. Often, in the process of writing the comment, I realize I’ve poorly named something or that I’ve failed to handle some case. Comments help guide the reader, but also the writer.
- convery 8y agoI usually just consider my opensource commits to be 'learning opportunities' for others; so I comment on every other line. It's actually pretty nice as a way of 'inlined duck debugging' that helps catch flawed reasoning, even when the code is 'obvious'. Example: https://github.com/Convery/Desktop_cpp/blob/VersionDD/Source/Appmain.cpp https://github.com/Convery/Desktop_cpp/blob/VersionDD/Source...
- bwilliams 8y agoI think that’s fine as a choice for a personal project, especially since your committed to it. It’s a totally different story when working with a team though. Comments become outdated, files get larger, and it becomes more of a hassle to maintain while providing little to no value most of the time.
- christophilus 8y agoComments becoming stale is a real problem. But it is one that is solved by code review and culture, not by fewer comments. In a team setting, comments like these are even more important, as it gives context and higher level meaning to the code without forcing you to jump all over the place through small functions (which would be an alternative way to make this self documenting.
- bwilliams 8y ago> comments like these I strongly disagree specifically about comments like these throughout an active code base. A well named variable or method can act as a much better descriptor of what’s happening and doesn’t have the same maintenance cost. I think we both agree that comments are valuable, just not the scope. Comments are valuable when you’re doing something unexpected or where the code fails to explain what’s happening. For what it’s worth I mostly work with Ruby, JavaScript, and TypeScript which definitely color my views.
- jrochkind1 8y ago> Comments becoming stale is a real problem. But it is one that is solved by code review and culture, not by fewer comments. Well, it can be both. Less code is easier to maintain than more code, and that applies to comments too. Finding the "goldilocks" point is the challenge of much code design, and it applies to comments too. There's such a thing as both more comments than you need (increasing maintenance cost and risk of outdated comments without providing enough value to justify), as well as less comments than you need (to decrease cost of understanding the codebase).
- VBprogrammer 8y ago// Have the window rendering in the highest allowed state. I'd argue that comments like these are fluff. It says basically the same as what the code does but doesn't say why it does that. In general I find comments like that suffer from bit rot faster than anything else (perhaps with the exception of commented out code) as it's tempting to leave the comment changes until you've got something working. And a wrong comment can lead you down the wrong path very quickly.
- convery 8y agoWell, ye. I mentioned that it was mainly for less experienced users to learn what the code does; and in this case it also tells the reader what the thread is responsible for.
- asterisk_ 8y agoI get where you're coming from with the 'inlined duck debugging' observation, however I'm of the opinion that explicitly commenting out "obvious" code chunks is usually fairly detrimental for a few reasons: (0. The debugging approach can depend on a person's mental model) 1. Readability - even for a beginner, the method name should give a fair indication of what the code does. If the method name doesn't give a good indication, then the name should be changed. Otherwise, the comment is redundant. 2. Staleness - imagine a commit which changes the behavior of Engine::Compositing::onFrame(Deltatime) to only notify some of the components about the new frame (comment currently states "// Notify all components about the new frame"). Presumably, this commit should only change the internals of the onFrame method. However, because of a redundant comment, the person who changed the onFrame method now also has to find all its invocations and possibly update many comments. My personal preference is commenting only domain-specific code chunks (example: [1]). These code chunks are usually put as close to the implementation as possible. This way, whenever someone wishes to change the code, the person (1) immediately notices reasons behind the implementation (and may decide against modifying the code if he/she was unaware of these details) and (2) can modify the comment right away in case domain-specifics have changed in the meantime. I'm curious to hear your or someone else's opinion against this argument? [1] https://github.com/tkukurin/lesshint-intellij-plugin/blob/master/src/co/kukurin/LesshintOutput.java#L57 https://github.com/tkukurin/lesshint-intellij-plugin/blob/ma...
- Carpetsmoker 8y agoThe rules in your last paragraph make perfect sense; documenting the purpose of the code is probably the most important. I think what is intended in general are comments in the form of: // Start the loop. while ( have_posts() ) : the_post(); [..] // End the loop. endwhile; And yes, that is an actual example from a real codebase. This is an extreme example, but quite a few of comments I see are very redundant. Sometimes comments are useful to split stuff up, but stuff like "start loop", yeh nah. It's just a random stray comment, probably as an artefact from when the author was gathering their thoughts and/or took a break. Even worse are comments that are just confusing, or don't match the code. I've done some literate programming, and I find it interesting for certain types of programs and/or if you're struggling with something. But I think that for a lot of stuff it's redundant.
- VBprogrammer 8y ago> Sometimes comments are useful to split stuff up So often when I see this I wish people would have used another function. Its hard to argue that a function which requires splitting things up using comments is "doing one thing".
- AlexCoventry 8y agoIt's supposed to do one thing at some level of abstraction/encapsulation. It can do multiple lower-level things in the service of that.
- hopler 8y agoFunction calls have clutter overhead.
- jdormit 8y agoThis is actually a bad example. "The Loop" is a concrete concept within WordPress: it's a global loop (shared across scripts) that represents the portion of the request processing spent looping through the posts that need to get rendered to the page. There are a number of WordPress API calls that only make sense when called from "in the loop", since they rely on global variables that get set in each iteration. Whether or not this is actually a good request handling model is much more debatable, but the comments in your example are meant to communicate that any code which needs to be called from The Loop should get called between them.
- laythea 8y agoWhat I don't like, is when companies adopt a policy that is checked for before code check in, such as in Java where there are many tools to perform the auto analysis of code. When one of these rules is "thou shall comment all declarations", it results in the developers polluting the code base with verbose drivel, to avoid the review-loop.
- aiisjustanif 8y agoMeanwhile I dislike the opposite at my company where all comments are banned.
- fiddlerwoaroof 8y agoOne of the reasons for this sort of policy often is that IDEs for untyped languages parse special comments for type information so they can provide autocomplete. (E.g. I’ve worked on PHP codebases where javadoc-style comments were required)
- laythea 8y agoThat sounds horrible. I hate code filled with that £(£U*$U&%", autocomplete or not :)
- userbinator 8y agoIt's the same with C#, and that naturally gives birth to tools like GhostDoc, which will automatically generate comments to satisfy those idiotic checks, even if the comments are completely useless to actual humans. (IMHO any comment that can be automatically generated has no value.) Thus the proliferation of comments like this: // FooBar - Foos the Bar // @param baz The baz. // @param quux The quux.
- harimau777 8y agoI have found that people who are able to defy conventional wisdom are, paradoxically, usually those who put even greater than normal focus on the core truth that the conventional wisdom is based upon. For example, someone on a team who is a "lovable jerk" is usually the person who, although rough in their presentation, is always willing to help others and put the team first. On the other hand, people who claim they are the exception to the rule usually do it as an excuse for not focusing on the core truth behind the rule. In the same way, I think the problem with "prefer code to comments" is that people often miss that it actually requires even greater focus on communicating your intention to others (e.g. via methods like declarative programming and meaningful names).
- rdsubhas 8y agoCan confirm. This is literally what happened in a codebase in the past: // OLD CODE WITH COMMENTS: // check ... 4 lines of code // drop ... 4 lines of code // read ... 4 lines of code // do xxx ... 4 lines of code In total, that method was like 16 lines of code, with some short commented sections. And the sections used variables from before. Situation: New coder comes in, sees comments. Says "comments are bad, they get out of date, yadda yadda". So proceeds to change comment names into method names: // PROPOSED: COMMENTS => METHODS check() drop() read() doxxx() What coder forgot was the variables and context. As said before, the total was 16 lines of code with simple variables used between it. Not a big deal. But now when it has to be split into functions, it became like this: // ACTUAL 1: COMMENTS => METHODS a, b, c = check() d, e = drop(b) f, g = read(a, d) i = doxxx(e, g) And this was a language that didn't support multiple return types. So the code was actually: // ACTUAL 2: COMMENTS => METHODS class X { a, b, c} class Y { d, e } class Z { f, g } X x = check() Y y = drop(x.b) Z z = read(x.a, y.d) i = doxxx(y.e, z.g) So now coder added 3 more classes, with more lines of boilerplate. Then the coder decided, to manage this problem better. So they created some more interfaces and did some DI. The result was around a 250 line PR, which I cannot ping here anymore. When we pointed out the same logic was now 250 lines, the answers were: "It's inherent complexity which we didn't know how to manage. His/her solution scales better, and he/she has shown us the way". All for what? Because comments were considered a smell. Go figure. I guess this is why this other HN post trended – "Please do not simplify this code": https://news.ycombinator.com/item?id=18772873 https://news.ycombinator.com/item?id=18772873
- Aardappel 8y agoThis might be a good interview question to identify net negative programmers like that. Give them the "ACTUAL 2" code, and ask them how to improve it. If they start talking about DI or any other additional abstractions, you have your red flag. And of course if the programmer asks "are X Y Z used anywhere else?" or has the balls to say "just inline it all into a linear flow of code", instant hire! :P
- christophilus 8y agoThis is exactly the example I had in mind, but didn’t have the patience to write up.
- sedatk 8y agoThat’s why I opt for “comment what code cannot tell”, I think it’s a great middle point and I don’t think it’s that hard to assess.
- deleted 8y ago[deleted]
- BurningFrog 8y agoWriting understandable code is a difficult problem. There is no simple trick that will make you just do it over night. > Code is (almost?) always obvious to you as you are writing it. I try hard to go back and reread code as I'm working on it, several times a day, as if I'm someone else, seeing it for the first time. It may help to pretend I'm showing it to a particular coworker. It's a certain kind of empathy skill that it takes work to develop, but it's very useful both for coding and any other writing. Perhaps the most common problem is what I call "assumed context". That is, you're so deep into the task that you take the major parts of it for granted and it never occurs to you to explain the most basic and fundamental parts of what you're doing. Instead you explain minor details.
- innocentoldguy 8y agoI comment my code because I've run into elegant, clean, self-documenting code that did the exact opposite of what it was a supposed to do. Comments let me, and other coders, know what I was trying to do, which I think is better than reading what I actually did and assuming it was correct.
- diminoten 8y agoYou would not be allowed to do any of this if you worked on my team. Do not put documentation in code, put it in documentation. Comments break up code, constantly flipping between reading the language and reading English. Comments are failures on the part of the programmer to describe the implementation clearly in the language being used. The lesson you should have learned is to recognize that it's okay to fail in this way, but to still consider it a failure.
- DSMan195276 8y agoI work on a team with the same policy, but personally I think it's a bit silly. There's nothing that guarentees that a version of the code that explains everything only in code is actually easier to undertsand, but that's the assumption being made. In a lot of cases I think it tends to be the opposite - adding more code just for the sake of 'explanation' bloats the code to much larger lengths and ends up making it harder to understand than if you just added a few lines of comments that explained the exact same thing. In that situation, adding comments is not a 'failure', it's just another option for making your code easy to understand.
- christophilus 8y agoYou wouldn’t be able to contribute to the Redis or SQLite codebases, then, as they are heavily and helpfully commented and are almost always near the top of the list of answers when people ask the question: “What are some examples of exemplary codebases?” In fact, it was reading those projects and then returning to my workplace’s uncommented source that convinced me to change my philosophy on commenting.
- kungtotte 8y agoI just looked up a sample of the SQLite codebase[0] and it seems to align with what most people are saying here, to keep a minimal amount of comments and the ones that are there should comment what the code can't tell you. [0] https://sqlite.org/src/fdiff?v1=7c288b4ce309b5a8&v2=8efa2c813b3f6a83 https://sqlite.org/src/fdiff?v1=7c288b4ce309b5a8&v2=8efa2c81...
- 8y ago
- userbinator 8y agoMy rule with comments is to use them at the "interesting" places in the code. I essentially treat them like a roadmap.
- Netcob 8y agoI think that conventions and a set of patterns explained (or at least listed) in the wiki/readme of a codebase go a long way. When I'm reading some API, then of course I want a detailed comment for each function and value, including valid/invalid parameters, maybe even some runtime behavior stuff if it's important (like whether some async method may contain some cpu-bound parts) any definitely anything unexpected or deviating from conventions. The conventions part being important because usually I don't have the time to read all the comments and all the documentation, but instead I'm looking for some simple concepts I can learn once and then use to understand most things just by reading the identifiers. If the project is written in a consistent way, it can be pretty large but require very few comments to be understandable. And anyone modifying it will need to know some set of rules for it anyway, so they should be made explicit.
- hopler 8y agoI don't understand how an article about writing less code would recommend adding more code to avoid comments.
- meowzero 8y agoI think that's why it's important to have regular code reviews or pull requests. At least, have someone look what you wrote. If they can't understand why you wrote a certain code block or do what it does, then either re-write it or explain in a comment.