18 ms·
Why Not Comments
- gary_0 2y agoThe title might be clearer with a hyphen: "Why-Not Comments".
- kstrauser 2y agoThe title's a little odd, unless it was to grab attention. It's saying "Why [I use] 'not comments'", not asking "why not comments?" A "not comment" here is an explanation of why the programmer didn't choose the obvious approach. I agree: that's a very valuable thing to document for the next person. For instance, you might write something like: # I used a bubble sort instead of a quick sort here because # the constraint above this guarantees there will never be # more than 5 items, so it's faster to use the naive # algorithm than to implement a more complex algorithm that # involves more branching. or # Normally we'd do X, but that broke customer Y's use case # based on their interpretation of our API docs which we # had kind of messed up. So now we do Y because it works # under both interpretations, at least until we can get # them to upgrade. Basically, tell your audience why you're not using the expected method. It's not because you didn't know about it, but because you do know and you've determined that it's not a good fit for this use case.
- lkrubner 2y agoThe problem with the title is simply that the English language allows open compound words. I know many Germans wonder why we allow this. Germans push the words together, for clarity. I've suggested that we use hyphens. Hyphens feel natural in English, and could remove the ambiguity that exists whenever we use open compound words (that is, open-compound-words). In this case "not-comments" would have added clarity. Likewise, the title "World's longest DJ set" was confusing, because most people will assume that the compound word is "DJ-set". But if you read the whole article, then you realize that a python snake fell on the mixing board and accidentally mixed some tunes. So the compound word was actually "longest-DJ" -- a 2.5 meter python. We should all consider using hyphens for all compound words. https://x.com/krubner/status/1828155852773113942 https://x.com/krubner/status/1828155852773113942
- BobaFloutist 2y agoI think the "Longest DJ Set" was intentional wordplay.
- thayne 2y agoAs was the title of this article.
- aidenn0 2y agoAs always, there's a relevant xkcd: https://xkcd.com/37/ https://xkcd.com/37/
- shiroiushi 2y ago>I've suggested that we use hyphens. Hyphens feel natural in English, and could remove the ambiguity that exists whenever we use open compound words We do use hyphens in English. Well, some of the time, and some of us. I could be wrong, but I do feel that, given my age and also my readings of older texts, that the use of hyphens in this way has become less common, and that this was much more common decades ago to avoid ambiguity.
- Tainnor 2y ago"longest DJ" isn't a compound, it's a noun modified by an adjective, and as such it would be written as two different words in German as well ("längster DJ").
- thayne 2y agoI think the title is intentionally ambiguous. Because the article is a rebuttal to those who oppose writing comments (that is where "why not comments" means "why you shouldn't write comments") where the main argument is that you should write "why not" comments (that is "why not comments" means write comments explaining why you didn't do something or do something a certain way).
- JohnMakin 2y agoI often write comments like this when I can predict what an overly nitpicky reviewer will say in a code review - "I didn't do X because Y" hoping to save some annoying back and forth about it.
- lainga 2y agoIME you get the same amount of back and forth but I get to write "as the comment says" a few times
- JohnMakin 2y agoLOL precisely
- rplnt 2y agoI add those preemptively in the PRs, but not sure they have much value in the code.
- not2b 2y agoThey have value in the code because they save time when someone has to deal with that code a couple of years later. Certainly the explanation could be in the code reviews or the commit message, but it's easiest if it is right there.
- panopticon 2y agoYup. Our operating principle was that if a question was asked in a code review, someone will likely have the same question when reading the code weeks/months/years from now and there should be a comment.
- TillE 2y agoIt's an obvious cliche, but that "someone" is very frequently you. It's really easy to forget why you made some non-obvious decision and waste time poking at the exact same stuff you already did a year or two ago. It's happened to me several times. When you figure out something tricky, leave a comment.
- Terr_ 2y ago> Does 16 passes over each string BUT there are only 25 math strings in the book so far and most are <5 characters. So it's still fast enough. Another twist on this is to put in a debug logging statement which triggers when the inputs are much larger than the original design constraints. It's roughly the same message to a future-developer, but they might find it much sooner, short-circuiting even more diagnostic and debugging time.
- ok_dad 2y agoThis is a great idea for a lot of things! Sometimes I will write a loop I know is slow as hell but works for now, and it would be cool to use a timer and do, "if this takes more than X seconds, log a warning." I mean, the perfect logging and observability should theoretically time all the components of your app, log debug information often, and etc., but who really uses a perfect system like that? I think it's more important to make specific effort to log in areas where performance might suck later or where you didn't have time to optimize or do exactly what you wanted to do. Your comment is super obvious, in hindsight, but I never thought to do something like this, usually at past places of work we've just agreed to make a comment on things we need to reconsider later and hopefully we remember about that comment when things go downhill!
- Terr_ 2y agoI'd caution that it's a very "80/20" thing, since the cost/complexity of detecting all "unusual" cases can easily become not-worth-it. For example, if the slowness of the method depends on non-trivial aspects of the input, or if the performance problem in production comes from someone calling your method too many times on (individually) reasonable chunks of data.
- CRConrad 2y ago> and etc The "et" in "etc" means "and", so you have that already.
- AlotOfReading 2y agoI find that a lot of well-meaning tools (e.g. bazel) regard non-error output as noise to be hidden. They'll often route any messages like this to the nearest wastebin they can find, which makes logging incredibly unreliable as a means of communicating constraints in some domains.
- ghewgill 2y agoI agree that the title is ambiguous - it's what piqued my interest to read the article in the first place. Personally I lean toward fewer comments overall - perhaps to a fault - but explanatory comments as shown in the article are absolutely valuable. It's a good reminder to explain the whys and the why nots. This especially applies to your own code that you write and still have to maintain 5, 10, 15 years later. Just the other day I was reviewing a coworker's new code and thought "why choose to do it this way?" when the reason was 10 lines up where I did it the same way, 8 years ago. She was following the cardinal rule of maintenance - make the code look like the existing code.
- sparrish 2y ago> make the code look like the existing code. This is so undervalued when maintaining an older codebase. Please, for the sanity of those who come after you - make the code look like the existing code.
- sbuttgereit 2y ago"Please, for the sanity of those who come after you - make the code look like the existing code." I think it's a great rule of thumb... but there are exceptions. For example, Funnily enough I was reviewing some code just today written by someone else and that I'm going to be asked to expand on or maintain. It looks like this: var example1 = Object; var example2 = Object; var example3 = Object; ... var example147 = Object; And then later there are corresponding variables assigned to different objects which are: var tempExample1 = <some object instantiation>; var tempExample2 = <some object instantiation>; var tempExample3 = <some object instantiation>; ... var tempExample147 = <some object instantiation>; And this goes on and on. It's real special once we get into the real business logic. (and to be clear... "example1" are the actual names, I'm not just obfuscating for this comment.) The reason it looks like this is because the original developer copied the examples from the developer technical documentation for what they were doing verbatim; this documentation only had one variable so the numbering was the way to get multiple variables. Knowing this system, they didn't have to do that, they could have very easily assigned meaningful names for all of this. (To be fair, the original developer isn't a developer but a consultant business analysist saying, "Oh yeah, I can do that!" to the client.... billing all the way). I can tell you with great certainty and righteousness: I'm not going to make my code look like the existing code. I may well do some refactoring to make the existing code vaguely scrutable. I appreciate that what I'm describing is an extreme case and not really what you or parent comments really were addressing. I just stop to point out that what you describe is a rule of thumb... a good one... but one nonetheless. And, as an absolute rule of thumb about rules of thumb, there are no absolute rules of thumb. Ultimately, experience and judgement do matter when approaching the development of new code or decades old code.
- ufo 2y agoWhen I see a sequence of string replacements, instead of performance the main thing I worry about is if the output of one replaces matches a pattern for another replacement. I see variations of this often during code review. Doesn't seem to be a problem here though because they're replacing macros by symbols that are known ahead of time.
- deleted 2y ago[deleted]
- remot_human 2y agoMaybe what we need is a single vocabulary word that means “I’m doing something that won’t scale well to large inputs but is still worth writing for now” then you could name the function replaceEscapeCharsNewWord()
- Jtsummers 2y agoI've named these things "naive" sometimes. Like "naiveQueryBuilder" or whatever the appropriate term would be. They're also useful for creating tests because the naive version is usually "obviously" correct (still write some tests, but you don't need much more than sanity checks) and can be the oracle for the faster version (you might want to cache results rather than run the naive one each time, though).
- xelxebar 2y agoIthkuil to the rescue? https://en.wikipedia.org/wiki/Ithkuil https://en.wikipedia.org/wiki/Ithkuil
- 8organicbits 2y agoAnother approach is ADRs, which document alternatives considered, but these are documentation, not comments. I've found them useful for building consensus around architecture decisions. https://adr.github.io/ https://adr.github.io/
- keybored 2y agoYou can still document the why in commit messages![1] I feel like I’m getting off the self-documenting code ride. In our own codebase we rely way too much on “descriptive names”. Like full-on sentence-names. And is the code self-documenting? Often not. You indeed cannot describe three or more axes of concerns in one name. Do comments go stale? Well why does it? Too loose code reviews? Pull requests that have fifty lines of diff noise that you glaze over? We have the tools to do better on that front than some years ago at least. It’s a joy to find a corner of the code base where things are documented with regular sentences. Compared to having to puzzle through five function call layers. [1] But yeah, really. But also: sometimes also in comments. Sometimes both.
- klingoff 2y agoRight, commit messages are at least always right for the context that comes with them. I think long descriptive names are an anti pattern. As per word puzzles you can't actually read the middle of a blob of text so you are basically left with a dozen variables that are cognitively the same as isDatabaseHidingDragonsSetter().
- oxidant 2y agoI mostly like a comment with a succinct explanation and a longer commit message. Comments are less likely to be refactored and lose the immediate git blame, while the function might change over time. Ideally the future user would trace the git blame back to the original commit of they really had questions. A long comment is really helpful sometimes though. I like to put ascii truth tables for complex boolean logic, both to ensure I cover all cases when writing the code (tests, too) and to make it easier for future me to understand what's going on at a glance.
- ok_dad 2y agoI personally don't care what anyone says, I use comments and doc comments ALL OVER the place; I do it in reverse, though. I write a list of steps for the application as comments, a rough draft at first, then as I develop the code I take the big steps and split them into little steps, sometimes removing the original comment and sometimes not, and I continue to split comments into smaller steps until I have nearly a complete algorithm. Then I just code the logic in there. I normally will code from the outside in, so I'll also be writing code as I do the comment-splitting stuff. Sometimes I get off on a tear and I code a bunch of stuff at once, but then later I go back and comment it down to a level that I think most of you would find annoying. Every function and variable has a comment about what it does, even the `deg_to_rad` function has a comment `"""Converts degrees to radians."""`. Why not, storage is cheap! I know most people don't like it, and that is fine, they can deal with it! I they don't want to see my comments, they can remove them from their version of my code with a script, and if my co-workers and boss don't like them they can remove them in a code review! However, I can say that I enjoy reading my old code way more than I enjoy reading other's code which have zero comments. I work in Python, so a lot of the simple non-algorithm code (boilerplate stuff for apps, like flask APIs for example) is mostly "self-documenting" since the old saying goes, "write some pseudo-code and 95% of the time it runs in Python." The most important comments are sometimes on the boilerplate stuff because that's where a lot of changes happen versus the algorithms where I find there is a lot more wholesale rewriting in my industry. I will always love comments and doc comments!
- buggy6257 2y ago> I know most people don't like it, and that is fine, they can deal with it! I they don't want to see my comments, they can remove them from their version of my code with a script, and if my co-workers and boss don't like them they can remove them in a code review! It was all great until you got here. This is a big red flag for me for a teammate.
- ok_dad 2y agoWell I don’t think we’ll end up being teammates, and I haven’t had issues before :)
- mentalgear 2y agoAn article not not to overlook.
- mentalgear 2y agoActually, there's a not to much (it was late), it's definitely a great article !
- jerhewet 2y agoComments should never be "what". They should always be "why".
- zimpenfish 2y agoThat works if the code wasn't written by, well, lunatics who decided that clear simple code was The Work Of Satan and if you couldn't have a tower of interfaces or write your own bafflingly complex ORM, what was even the point? Then the people who follow will almost certainly need some "what" commentary (as well as the "why" but IME the lunatics who spurn clear and simple code never think they have to explain "why" either.)
- mschuster91 2y ago> or write your own bafflingly complex ORM Oftentimes, the reason for that is that 20 years ago stuff like Doctrine, Liquibase or whatever just didn't exist. You know, the time when PHP developers shipped straight mysql_query calls with direct interpolation of $_GET, and most "enterprise" Java application came with a ton of SQL scripts and a dedicated multi page UPGRADE file explaining in which order you had to run the schema migrations, reboot systems, run manual migration scripts and whatnot to get an upgrade done. Some times, upgrades could literally take days. Naturally, people invented their own stuff to make stuff just suck a little bit less, and it got more and more used in a company, only ever extended in functionality... the dreaded "corpname-utils" JAR dependency (if you're really unlucky, the JAR having been semi-restored from a half-broken decompile because the sources got lost along the way) or util.php that just got copied over from project to project. And that's how you end up in 2024, still maintaining some ORM that has its origins in Perl code written in the 90s by someone deceased in the '00s. (Yes, I've been there, although not that bad)
- pantulis 2y ago> the dreaded "corpname-utils" JAR dependency In my first job, my older colleagues, most of them now managers, had managed to write their own library. It included its own timezone management, a wrapper o top of DEC's OSF/1 AXP concurrency primitives, a realtime memory-mapped database format, a compiler that run not on files but in expressions stored in an Oracle databse, and even their own CORBA-like object sharing over TCP/IP. These people were wizards, and probably did a lot of stuff just to show their coding prowess, but a decade later when I joined that company most of the younger programmers did not dare to touch that code. I had to do that when the software was being deployed in Brazil, where nobody had expected how DST changes in the south hemisphere.
- renhanxue 2y agoI saw someone quip (on twitter, I think) many years ago something like: "A junior engineer writes comments that explain what the code does. A mid-level engineer writes comments that explain why the code does what it does. A senior engineer writes comments that explain why the code isn't written in another way." (except punchier, of course. I'm not doing the quip justice here)
- abc-1 2y agoI do all of the above. Summary comments are incredibly helpful and have been validated by empirical research. Too bad many have drunk deeply from the Clean Code koolaid and can’t be saved.
- Prickle 2y agoI was taught to not leave comments in finished code. I have regretted following that lesson ever since.
- acbart 2y agoIf code were ever finished, then perhaps this would make sense :)
- spacechild1 2y agoWho taught you that!?
- Prickle 2y agoI was specifically taught that good, readable code could explain itself; that it would make comments redundant. Therefore, comments should only be used for things like psuedocode, or as help for fellow developers during dev. Then, they should be removed once the code is done. But yea, not a good idea.
- thayne 2y ago
- breck 2y agoI resisted putting comments in my languages for years. My reasoning was it was always a flaw of my code (or the language) if I couldn't express myself in typed code. Then I realized that my languages will never be perfect, and having comments is an essential escape hatch. I was wrong and I changed my mind. Also, 99.9% of languages have comments: https://pldb.io/blog/a-language-without-comments.html https://pldb.io/blog/a-language-without-comments.html
- icambron 2y agoThe “why not” form just seems to be a special case of “explain why this code is weird”, which is my commenting metric in its entirety
- golergka 2y ago> This is incredibly inefficient and I could instead do all 16 replacements in a single pass. But that would be a more complicated solution. So I did the simple way with a comment: > Does 16 passes over each string > BUT there are only 25 math strings in the book so far and most are <5 characters. > So it's still fast enough. I've been in this exact situation quite a few times — use a bad algorithm because your n is low. However, instead of commenting, I did something like this instead: function doStuff(items: Item[]) { if (items.length > 50) { logger.warn("there's too much stuff, this processing is O(n^2)!"); } // ... do stuff }
- Wowfunhappy 2y ago> When I was first playing with this idea, someone told me that my negative comment isn't necessary, just name the function RunFewerTimesSlowerAndSimplerAlgorithmAfterConsideringTradeOffs. Wow, someone actually suggested that?! Do people write whole programs like this?
- mkoubaa 2y agoThis is griefing your coworkers who would actually do that?
- Wowfunhappy 2y agoI wasn't being sarcastic, if that's what you mean. (And I'm not a professional programmer, so my coworkers don't write code.) To me, the suggestion seems so incredibly bad that it leaves me wondering about the headspace of someone who would suggest that. Is it somehow less bad than it seems?
- herpdyderp 2y agoYes. I currently work in a codebase where the previous tech lead did that and promoted such behavior (among many other insanity-inducing practices).
- mgsouth 2y agoThere are many, many developers who are, deep in their hearts, "programmers"--someone who creates a plan of action, a program, for very complex machines to follow. They are skilled at discerning The Right Way to solve a problem. Actually, THE Right Way. And since they are Programmers, the Right Way is to find the Best Way to tell the computer what to do. Computers are completely oblivious to comments, so they aren't The Best Way. Comments are ambiguous, so they can't be THE Right Way. Computers parse identifiers, so a good variable name is telling the computer _something_ at least, and so is vastly preferrable to comments. If there's a mismatch between comment and code, the code is Reality so the comment must be wrong, and is thus misleading and worse than useless. In reality, of course, software development is about getting large groups of people in-sync as to problem, solution, and implementation. That takes lots and lots of communication. Ambiguous, messy people-to-people stuff, without The Right Solution to contents or wording. Because there's a bias towards thinking of the Program as Reality, it never occurs to such developers that an identifier can become just as outdated or wrong as a comment, and in fact it is easier to correct a comment than to globally rename identifiers, or that a 20-word comment carries vastly more information and nuance than a 20-character function name, or that trying to shoehorn information important to developers into a language used to tell _computers_ how to function is worse than trying to drop assembly language into a SQL query.
- GuB-42 2y agoI'd say that it is one of the few cases where comments are the best solution. You can't have functional code for what isn't done, so that's some information you can't express in code. Furthermore, a major problem with comments is that you can't debug or test them. There are many tools that can analyze code, static or runtime, but because comments are just free text, you can't do much besides spellchecking. Also it is common to forget to update comments, and with the lack of testing, in the end, you get lies. But here, the only maintenance these comment need is to remove them if they stop being relevant. For example because you finally did the thing you said you wouldn't do, or just scrapped the part. Very low effort, also rather easy to spot, since if you see a thing being done with an explanation on why it is not done, it means someone forgot. It is also worthwhile because as programs grow, they tend to do more, and "not" assumption may no longer hold (there used to be 4 parameters, now there are 10000...), meaning it is something you should check. A lot of slow code comes from an assumption that N will be small, and N ends up being big. By the way, that's why I favor using the lowest O(n) algorithm that is reasonable even if it is overkill and slower on small sets. Because one day, it may not be. If for some reason, using a low O(n) algorithm is problematic, for example because the code is too complex or the slowdown on smaller sets too great, then comes the "why not" comment.
- hughesjj 2y agoIt would be super cool if you could provide a list of line ranges for comments. Like "this comment covers lines 12-14". I suppose if you make the refer nces fancy enough you wind up reinventing rst
- RandallBrown 2y agoThis is actually really easy to do in most languages by wrapping the code you want to comment in a function. func uglyHackForCombiningTwoThings() { // Do whatever ugly thing you want to do }
- GuB-42 2y agoYou don't need a function, a simple {} block is enough if the language supports it. Some languages (ex: Python) don't have that though, you may need a function, or some other construct (ex: if true) in this case.
- deleted 2y ago[deleted]
- AcerbicZero 2y agoI have learned to enjoy narrating my struggles in the comments, probably to excess; but it certainly makes it much easier to pick up a task again after I leave it alone for a week or two. People rarely touch what I write, but if they do, and they want to strip the comments out, thats totally fine with me, just don't ask me how it works after you do :P
- matt_lee 2y ago> Why not "why not" comments? Not why "not comments" I nearly exploded trying to grok this
- giraffe_lady 2y agou can tell this dude loves algebra
- slaymaker1907 2y ago> In recent years I see more people arguing that whys do not belong in comments either, that they can be embedded into LongFunctionNames or the names of test cases. Who is arguing this? Usually, if I'm adding a comment on why something is done a particular way, it's something that is going to take at least a full sentence to explain if not a whole paragraph.
- philipwhiuk 2y agoPersonally I think you're better off putting 'not comments' in git commit information. Git commit comments are like normal comments except they don't get detached from the code.
- jakub_g 2y agoI believe this can work in slow paced opensource projects which do squash-merges (one PR = one commit), every commit is green and beautiful and well described with properly formatted message. I worked on such project in my first job and I cared a lot about my commit messages, and changelogs. On the other hand, in fast paced corporate development I barely ever see someone make commit messages like this. Even PR titles often leave a lot to be desired.
- keybored 2y agoSquash merging is a practice I mostly see recommended (I mean: mandated) from those corporate environments which churn out code like a paper mill trying to put the Amazon out of existence. OSS projects that can take their time with nice commit messages—which even review them, not just the code—don’t have to limit themselves like that.
- jakub_g 2y agoApart from what/why/why not: Something I started doing recently is to put URLs in the comments: - URL of documentation for a complex feature - URL with a dashboard with telemetry - URL of a monitor which checks if the given feature, CI job, GitHub action etc. works correctly. In a big project, figuring this stuff out is not trivial, requires a lot of searching with proper search terms and/or asking the proper knowledgeable person. I find it weird that code is often so detached from everything non-code.
- deleted 2y ago[deleted]
- jesse__ 2y agoI ascribe to the notion that 'comments are apologies' (to my future self). If a piece of code is weird, or slow, or you'd say "yeah, it's kinda janky" when describing to somebody, I usually write a comment about it. Especially if I've changed it before; to document some case that didn't work, or I fixed, or whatever. When you operate on this basis, superfluous comments just melt away, and you typically end up documenting 'why' only when it's really necessary. Try it out in your own codebase for a month and see how it feels :)
- gregmac 2y ago> I see more people arguing that whys do not belong in comments either, that they can be embedded into LongFunctionNames or the names of test cases. Virtually all "self-documenting" codebases add documentation through the addition of identifiers. Identifiers can go a _long_ way, but not _all_ the way. I personally am a fan of requiring documentation on any public methods or variables/fields/parameters (using jsdocs/xmldoc/etc). Having a good name for the method is important, but having to write a quick blurb about what it does helps to make it even clearer, and more importantly, points out obvious flaws: * Often even the first sentence will cause you to realize there's a better name for the method * If you start using "and" in the description, it is a good indication that the method does too much and can be broken down in a more logical way People often think properties are so clear they don't need docs, then write things like: /** The API key */ string ApiKey; But there's so much missing: where does this key come from? Is this only internal or is it passed from/to external systems? Is this required, and can it be null or empty? Is there a maximum? What happens if a bad value (whatever that is) is used? Is there a spot in code or other docs where I could read more (or all these questions are already answered)? This is stuff that as the original author of the code you know and can write in a minute or two, but as a newcomer -- whether modifying it, using it, or just parachuted in to fix a bug years later -- could take _hours_ to figure out.
- yodsanklai 2y agoThis seems a bit like a strawman argument. I don't think anybody say that we should never use comments. The problem with comments is that they can become stale, and it's often possible to self-document or write simpler code that causes less surprise. But of course, it's totally fine to put comments. And I think comments should be mandatory for interfaces functions/types unless their behavior is obvious. I don't want to read the code to understand what a function does, or what invariant a class maintains. And if it's too complex to document in a few lines, probably this isn't the right interface. But apparently, this isn't obvious for everybody. In my company, most of the code isn't documented.
- boerseth 2y ago>The negative comment tells me that I knew this was slow code, looked into the alternatives, and decided against optimizing. I admire the honesty, but will continue to phrase these "why not" comments as insincere TODOs.
- anotherevan 2y agoI think the favourite type of comment I've ever left in my code follows this template: DEAR MAINTAINER: This code is the way it is because of <reasons go here>. Once you are done trying to 'fix' this, and have realised what a terrible mistake that was, please increment the counter as a warning to the next person: total_hours_wasted_here = n I'm not the original author, but have gratefully used it once or twice, and been amused when there was a single line commit incrementing the counter.
- tombert 2y agoI wish I had had this years ago. I one time wrote this fairly elaborate SQL generation thing that required pretty liberal use of recursion in order to fulfill all the requirements. It ended up being a lot of mutual recursion and the code was admittedly kind of messy but it was a necessary evil to do everything asked of me. A more senior engineer ended up taking over the codebase, "fixed" all my code to be this iterative thing, made a point to try and lecture me about why recursion is bad in an email, only for his code to not actually do everything required and him reinventing effectively everything I did with recursion. In fairness, he did actually apologize to me for some of the comments he made, but if I had thought about putting this comment on the top maybe we could have avoided the whole thing.
- bccdee 2y agoI've never heard anyone say recursion is bad. What a weird view. It's a problem if you're overflowing the stack, of course, but otherwise…
- spencerchubb 2y agoMy team comments way too much. I constantly see stuff like this def fetch_data(comment_id): Args: - comment_id: The id of the comment to fetch. Returns: The comment data # Fetch comment data data = fetchCommentData()
- Minor49er 2y agoMine do this as well, but in PHP. They adopted docblocks over a decade ago and never defined any best practices or used any tools to check them, so comments don't even match the code half of the time. We're on PHP 8 now which can enforce types in the code itself but still have to include docblock types because that's how it has always been done, so the problem persists. It's maddening
- zwnow 2y agoComments tend to get outdated quickly as your app grows. If you are not careful with your phrasing you might even introduce misinformation into your app. I'd rather read the code instead of comments.
- jimmaswell 2y agoI love when a docstring saves me from reading code. "Takes parameter x which should be in state s, has side effect e, returns j, throws exception if .." Seeing that in my IDE popup and moving on with all the info I need is so satisfying compared to having to waste my time on an unwanted spelunk. It's also impossible to embed all this in a name that isn't a camelcase paragraph.
- zwnow 2y agoI can imagine that this is helpful to some people, but when coding I ignore comments usually. Good docs and code is all I need.
- at_a_remove 2y agoAlthough I had started programming when I was nine, in high school I was fortunate enough to have a computer science teacher with a PhD in the field. Among one of the habits drilled into me was extensive commenting. Every function (or procedure) starts with a comment block. It first talks about the what and why. Then, a line for the inputs and another for the outputs. Next -- and this is done closer to the end of the writing -- I describe what it calls and what it is called by. The comment block optionally finishes with room for improvement. The function itself probably has other comments. Usually for anything which is not blindingly obvious. Because I write code like a caveman, wherein only one thing happens on one line, most everything is quite clear. If there's anything weird or magical that has to happen, it gets a comment. Elegance and cleverness is reserved for data structures, algorithms, and so on, rather than doing a lot of stuff in as few lines as possible. I do this for Future Me, who might be having a bad day, or for anyone who wants to adapt my code to something else. One of the last steps in a finished program is going through and making sure that my comments match my code. I am a very boring kind of programmer.
- kqr 2y agoAnother big one I wish I saw more often is "these are the circumstances under which this assumption was made and here are the steps you can take to check if those circumstances have meaningfully changed." In other words, the comment allows the author to reach into the future and co-debug with the reader, even if the author is no longer there.
- ktosobcy 2y agoI somewhat dislike the notion of "self-explanatory code" (especially if someone has tendency to be "smart")... optimise for reading and add comments!
- analog31 2y agoOne issue with comments is that an engineer who struggles to write clearly will also struggle to write clear comments. And clear code. But at least the code can be deciphered by reverse engineering it, stepping through it, or in some cases rewriting it. For me, at least the comments are worth reading before trying to figure out what someone's code does, to get me into the ballpark. I often add comments to code as I decipher it, then remove them again when I figure things out.
- geraldwhen 2y agoAn engineer who struggles to write clearly is one I would hope not to hire. Programming is first and foremost a problem discovery job, then a writing job, then math and logic. No matter how efficient or eloquent, if you solve the wrong problem, you’re doing no one any good. Solve the right problem efficiently, but in a way no others can understand, and you’ll flounder in a team. You will also never be able to collaborate or make larger work move faster. Correct problem, clear writing, then logic.
- analog31 2y agoI definitely agree, but still, a lot of people are told "you will never use your math or writing after college." It may also be that they perceive themselves to be judged by how much code they can sling, and not the quality of their writing. And in a large enough department, the work that depends on math ends up being given to the one or two "math people." I'm one of those. But I suspect that there's a relationship: If their writing is hard to read, their code will be hard to read.
- veltas 2y agoWhy not question-mark?
- Timwi 2y agoThis is just a special case of a broader, more general advice that I follow: Comment on whatever would be surprising when you read the code. When I write code, a voice in the back of my head constantly asks “will I understand this code later?”. (People who just instinctively answer ‘yes’ every time are arrogant and often wrong.) Whenever the answer is ‘not sure’, the next obvious question is “why not?”. Answering that question leads you directly to what you need to write in your comment. Sometimes the answer is “because the reader of the code might wonder why I didn't write it another way”, and that's the special case this article covers. But sometimes the answer is “because it's not obvious how it works or why it's correct” and that clearly requires a different type of comment.
- perlgeek 2y agoAs an addition, if you first try to write the code one way, and then it doesn't work and you need a second approach, that's a really good indication that you want some kind of comment there. You were surprised while writing it, so if you'll forget that surprise in a year, you'll be surprised by reading it too.
- albrewer 2y ago> “will I understand this code later?” My driving principle in the same vein is "where do I have to look when/if this doesn't behave as expected?" - if the answer is not in the docs (wiki -> package/module -> file -> class -> function / method) or is otherwise > 10 lines away, it gets an inline comment (or the docs are updated). Usually this happens when chopping up strings or during intermediate navigation steps over an odd data structure.
- narag 2y agoI comment everything that I think would be useful for me when revisiting the code a year later. Usually "why" and "why not". Sometimes a short "what" when the code is complex and it's nice to see the sequence more clearly. What's not so useful: mandatory comments. A public API should be thoroughly documented, but some shops insist on writing comments for every function in the code, even private ones and even if its purpose is so obvious that the comment just rephrases its name. This practice is not only a waste of time, but also insensitizes you about comments and teach you to ignore them. Other wasteful comments are added by some tools. I hate the one that marks every loop wiht a //for or //try comment.
- cjfd 2y agoYes, completely agree. Also, too many comments make it difficult to see what is in a class/function. If the comments make a class/function that would otherwise fit on one screen no longer fit on one screen there is a readability cost to this.
- exe34 2y agoI wish they would put the comments before the function name in python, as otherwise the useful code is separated by useless verbiage. I also wish comments would include examples of the shape and dtype of inputs and outputs.
- BeetleB 2y agoCollapsing/hiding comments should be a required feature in editors. In Leo[1], you can make nodes out of them and just hide them. If Emacs weren't so good, I'd be using Leo. Similar power when it comes to extensibility, but extended via Python, not elisp. [1] https://leo-editor.github.io/leo-editor/ https://leo-editor.github.io/leo-editor/
- gwervc 2y ago> Usually "why" and "why not" Related anecdote: yesterday I was on a code portion of a personal project with a "Is this really useful?" comment on a line that seemed it could easily be removed. I tried to use the newer and cleaner class instead and the particular old way was indeed needed. So I appended a "=> yes!" to the existing comment as well. I'm glad my former self documented the interrogation. At work, especially on bugfix, I often write a one or two lines comment with the ticket issue number over a non-obvious change.
- pwdisswordfishz 2y ago> Why not "why not" comments? Not why "not comments" Or you know, you could have just used a hyphen instead of clickbaiting.
- dekervin 2y agoI am working on the abandonned idea of a rapgenius for code. I think it still is a useful idea for the open source world. You can join the HN learn discord [1] if you want, so I can keep you posted. [1] https://discord.gg/ks4yfPgbyn https://discord.gg/ks4yfPgbyn
- agentultra 2y agoMay also sometimes, when designing algorithms, be useful for documenting pre- and post-conditions and invariants in procedural languages that lack embedding such specifications. You can't really reason about these things in the language itself and end up having to use something else (predicate calculus usually) but it's nice to at least have an indicator, as tfa suggests! What code doesn't do is important!
- pdpi 2y agoI find myself following only two or three different patterns in comments: There's often a fairly small kernel of very dense code that abstracts away a bunch of complexity. That code tends to have well north of a 1:1 comment to code ratio, discussing invariants, expectations, which corner cases need special handling and which ones are solved through the overall structure, etc. Then there's a bunch of code that build on that kernel, that is as close to purely declarative as possible, and aims for that "self-documenting code that requires no comments" ideal. Finally, there's the business logic-y code that just can't be meaningfully abstracted and is sometimes non-obvious. Comments here are much more erratic and often point at JIRA tickets, or other such things.
- aurelien 2y agoBBBbbbbeeeeccccaaausssseeeeEEEE!!!!
- yawnxyz 2y agoin the age of AI and Cursor, I make my function name as expressive as I can, and I make sure to add a couple of lines of comments, either generated or manual. It makes it way easier to send these into Claude (it seems, at least). I hope they introduce a semantic/vibes search too as I can never remember what I name my classes and functions...
- k__ 2y agoWould be cool if literate programming caught on. It seems only to be a thing with Jupyter notebooks, and even there it mostly describes the results and not the code.
- mark-r 2y agoI once wrote a bubble sort into production code, because the total number of elements to sort rarely exceeded 4 and it was what I could do off the top of my head. I don't remember if I left a comment explaining the reasoning, but I think I did. A year later a new feature invalidated my assumption about the number of elements and the sort was way too slow. I'm sure the person who inherited that code cursed me a few times.
- flerchin 2y agoComments and docs are lies that I dearly love. I want and need them, but I never forget that they're, at best, helpful lies. The code does exactly what's written, the comments adhere more or less, sometimes.
- tombert 2y agoMy rule of thumb has been "comment stuff that isn't the naive solution", basically anything that would make someone think "wtf is this" the first time they read it. My biggest headache right now has been getting high-throughput with SQL and as such I've had to do a lot of non-obvious things with batching and non-blocking IO in Java to get the performance I really need, and as such a of the "obvious" solutions don't work (at least with a reasonable amount of memory). Consequently I've been pretty liberally commenting large segments of my code so that someone doesn't come in and start bitching about how "bad" my code is [1], "fix" it, and then make everything worse by rewriting it in a more naive way that ends up not fulfilling the requirements. [1] I have since stopped doing this, but I'm certainly guilty of doing this in the past.
- W0lf 2y agoMy rule of thumb for code comments is to comment what's not in the code.
- kazinator 2y agoMost comments belong in the git log message. That's where you want to discuss the "why not". You have all the space you need in order to do that, without cluttering the code. The log message will accurately pertain to the change made at that time. When commits are rebased, the log message must be revisited and revised. Changes can disappear on rebasing; e.g. when a change goes into a baseline in which someone else made some of the exact same changes in an earlier commit, so that the delta to the new parent is a smaller patch. In my experience, commit messages stay relevant under most rebasing. Comments are (largely) an obsolete version of version control log messages. In the 1980s, there was a transitional practice: write log messages, but interpolate them into the checked out code with the RCS $Log$ thing. This was horrible; it practically begs for merge conflicts. It was understandable why; version control systems were not ubiquitous, let alone decentralized. You were not getting anyone's RCS ",v" file or whatever. Today, we would be a few decades past all that now. No $Log$ and few comments. Mainly, the comments that make sense today are ones which drive automatic API documentation. It would not be reasonable to reconstruct that out of the git history. These API comments must be carefully structured so the documentation system can parse them, and must be rigorously maintained up-to-date when the API changes.
- thehappyfellow 2y agoHow am I supposed to be aware of a commit message specifying the “why not” when reading the code later down the line? I could easily imagine somebody refactoring code to an obviously better version, finding out it doesn’t work for subtle reasons, running got blame and cursing the person who left that information in a commit message instead of a comment.
- kazinator 2y agoThat's a different kind of why not: about why we didn't do it in this seemingly obvious incorrect way, but had to do it in a more complicated correct way. If that obvious incorrect way happens to match what you're thinking of doing, then that kind of why-not documentation will help. Warning future developers not to make certain changes is indeed something that should go in a comment. We can make a short comment like, /* if you think you can rewrite this in a simpler way, read commit df037acb first */ There are unfortunate situations when things have to be changed in multiple places together; you must not forget all of them. That deserves comments. If you have an enumeration that has to pack into 3 bits, there should be a comment warning not to add more elements than eight without increasing the number of bits; especially if there is no compile time assertion for it.
- deodar 2y agoThere is no hope for the software industry to mature if we cannot agree on some basic coding practices. Like the judicious use of comments to improve maintainability.
- worik 2y agoI have had the experience this year of working on a system with 150k lines of C ant 150k of Typescript. The gentleman who wrote it in 36 months quit and here I am. He did not believe in comments, much. I think he thought he was commenting the hard stuff, mēh, I am unsure. It has led me into strong opinions. * Document every function. The function should make clear what the preconditions, preconditions, and the purpose are * Docunebnt every file/code unit. Why it exists * Document important loops like functions * Document the easy stuff. It is not easy if unfamiliar * Review the comments when working on code This would have saved my company about thirty percent of my time. The compiler does not verify comments, like it does code, so it is a burden. Bad programmers get another opportunity to sow chaos, I know. But one of the main purposes of code is communication with following humans, as well as controlling machines Careful and thoughtful comments are a professional obligation IMO
- obelos 2y agoDo you really need to comment to yourself or anyone else that you did a thing the less efficient way because it was simpler? I guess I"m not seeing the use. When later you've perturbed the criteria that caused that function's inefficiency to be immaterial to overall performance needs and it suddenly becomes material, profiling is going to reveal the low-hanging fruit faster than digging through the code for a “this could be faster a different way” comments.
- wwarner 2y agoI would call this “defensive coding”, analogous to defensive driving. And comments that talk about something that isn’t there is way too defensive, kind of like the excessive braking and overly polite waving that can make 4 way stops so confusing. Write your code clearly, keep your functions wholly visible without scrolling, keep the comments to a minimum, and put the ideas that can’t be expressed as code in a README.
- fennecbutt 2y agoA lot of anti comment crowd are because "good code should be understandable without comments" which I think is just elitist snobbery. Sure people can tell what the code is doing over a file but comments could definitely add a little more context of what the code is _for_.