7 ms·
The comment:code ratio is higher than anything I write or that I’ve seen. However, it does give me some comfort. When it’s not gamed, do other HNers also feel
by startupdiscuss 8y ago
The comment:code ratio is higher than anything I write or that I’ve seen.
However, it does give me some comfort. When it’s not gamed, do other HNers also feel that a high comment:code ratio probably indicates quality?
There are reasons why this may be the case. (More thought, more time and a large team etc)
I don’t advocate using this measure to reward anyone because it would be gamed immediately.
- lmm 8y agoI think it's likely to indicate low quality. Comments are for where the code wasn't clear enough.
- macintux 8y agoIt is rare to find code that comprehensively explains (without comments) why it exists, or often more importantly, why some superficially-equivalent code doesn’t exist there. Comments when done correctly are vital.
- mdpopescu 8y agoSo are politicians when not lying and well-behaved children. Correctly done comments are a one in a million thing. In my experience, they are utterly surpassed by "i = i + 1; // increment i" style comments. (Seriously, I'm working on code written by someone who teaches programming and he writes this type of comment.)
- AlexCoventry 8y agoIn an actual teaching context, a comment like that can make sense.
- jopsen 8y agoSome languages like golang, doesn't priorities concise code, it often takes a few lines to do something trivial. Find the object in a list with the lowest lexicographical ranked value of some property. The code to do this is simple, but not concise, leaving a comment so I can scan the function and skip 5-10 lines doing something trivial is nice.
- c3534l 8y agoThis sounds like a self-fulfilling prophesy. If only think comments are for telling you what a line of code does literally, then you're only going to see comments where the code is obscure. If you use it as a form of high-level communication to help the user understand the broader context and reasoning behind code (like at the top of the linked page), then it will be useful because the person writing the comments understands why documenting your code is a good thing.
- lmm 8y agoCode can and should be a form of high-level communication too. In a well-structured program, the high-level code will explain the high-level context, and the low-level detailed code will explain the low-level details.
- dllthomas 8y agoMaybe a loose correlation? Highly commented code was probably not written under tremendous time pressure; uncommented code can go either way. Wrongly commented code is painful, though. And then there's something I recall running into, a decade ago: using namespace std; // using namespace standard
- celeritascelery 8y agoI always wondered what std stood for /s
- dllthomas 8y agoInorite? It wasn't even "using standard namespace"...
- bdibs 8y agoI actually would say it’s almost the opposite, if you’re writing clean, expressive code it shouldn’t need explaining. And if your code is clean, you shouldn’t have a bunch of redundant comments explaining the obvious.
- eponeponepon 8y agoWhile your fundamental point is very valid, there are plenty of times where a comment to flag up a fine point of your clean and precise code will save future-you hours of head-scratching. I absolutely do not comment enough, but knowing this, I try to stick to the principle that if I have had to stop and think through an expression before I write it, then I am likely to eventually thank myself for leaving a short explanatory note. And moreover, it may not be me scratching my head over that nest of ternaries in a year's time - it may be some other poor soul. And while that poor soul won't thank me for leaving a comment, he or she will certainly curse my name - quite possibly vocally and publicly - for not leaving one.
- bdibs 8y agoOf course, there are certain times like you said when you should 100% add a comment. There’s nothing worse than going back to a codebase from a year ago and seeing a couple magic numbers and having no clue how they came to be, haha.
- geofft 8y agoI'm not sure there are many cases where there should be long amounts of expressive code. If you're doing something obvious, you should generally be able to program it concisely, in which case you have a high comment-to-code ratio because the amount of code is low. Sometimes this will be because you're importing an external library to do something, or because you're calling out to an internal library. Sometimes this will be because you found a straightforward implementation. If you're finding yourself writing hundreds of lines of code to do a single obvious task then chances are high you're implementing it poorly (and, specifically, in a way where your defect rate is likely proportional to the number of lines of code). And if you're doing several obvious things, then the point of the code is not to explain what the code is doing, but why it's doing that. What is the business purpose of the code? Which customer cares about this edge case that you're handling, and under what circumstances can you stop handling it? Why did you decide that the common library wouldn't actually work here? If you're converting data from an awful legacy format, why are your ingesters / parsers for the legacy format designed in this way? If you're micro-optimizing for performance, why are the optimizations sound (i.e., why do they accomplish the same thing as the unoptimized version), how do they work, and why did you decide these spots need to be optimized? Each individual thing you do might be obvious on its own, but the arrangement of the whole thing needs comments for each step, which again gives you a high comment-to-code ratio.
- sl1ck731 8y agoI think it indicates pride more than anything. If I write something that is just business as usual or commonplace my comments are pretty lacking. If it is something very interesting or that I am proud to have done, I usually write some very detailed comments. This probably correlates to better quality just because it was something I was interested in doing rather than shoveling code.
- existencebox 8y agoI think it's situationally useful. If I take the author of the OP code at their word, this is one of those situations. Core, critical plumbing/logic at the kernel of business critical, long-lived applications, will be the source of my stress-dreams long into the twilight years of my life; in the form of a lack of documentation and a presence of organic growth. To criticize myself quite bluntly: If the core code I worked on at work looked like this, I'd feel a great deal more comfortable in some of the changes/digging that inevitably arises. I would never use it as an absolute metric; but I'd use the level of comfort e.g. a new dev feels when looking at something that might otherwise be a spiderweb and saying "Oh this makes sense" (As I do when looking at OP) as a north star for the most sensitive bits of logic.
- sleepybrett 8y agoAs a user of this particular code, and someone who found several bugs in it in the early kubernetes days that were very hard to trace. I applaud the hell out of this.
- galangalalgol 8y agoWhy isn't the core code not most of the code? Why isn't it all core code with a tiny dash of ux or data access sprinkled on it? With, maybe, one abstraction layer somewhere (but never two touching!l.
- thockingoog 8y agoAs one of the authors of the original code here, this was the result of several days of intense works by a half dozen people working through every corner case we could dream up, and a bunch we thought of on the spot. It is in no way a guarantee that we got them all, but after spending so much time reason in through why those 'else' clauses were correctly empty, we thought it would be rude not to write it down. In truth it was as much for future-me as anyone. My memory is know. To be spotty. :)
- boulos 8y agoTim, does someone have a fuzzer running against this? Or even some static analysis ensuring that say the enums from various things are actually handled?
- spyspy 8y agoLong comments tend to scare me because they often detail some horrific hack that I'm going to have to deal with.
- majikandy 8y agoSo true.
- nerdponx 8y agoKnuth allegedly attributes the stability of TeX to his literate programming style.
- vharuck 8y agoI was reminded of Knuth, too. The code/comment blend encourages reading it like a white paper.
- rasengan 8y agoI comment to myself before I write code. It’s in English. Then I write code. So every line of code is commented by default. I think this provides me higher quality, less bug ridden results. So if others use comments in this style I would tend to believe it does increase code quality. If a line of code doesn’t match the comment, something is clearly wrong. ;)
- namuol 8y agoI use comments to document assumptions that are likely to be wrong, either now as I write it, or later when someone (probably myself) changes it. It is absolutely useful to do, and really not too difficult. Languages that allow for more formal assumption-checking (especially before runtime) are even better, but comments have an additional benefit of being understood by a human directly. I wish languages with static analysis could somehow allow authors to encode human-friendly/sematic errors that you often see as runtime exceptions into the static analysis itself...
- kakarot 8y agoSometimes it's good to have a block comment explaining the motivation behind a chunk of code or particular line, or just to clarify the individual steps in small modules, but you have to remember you aren't writing prose. I think around 10% of your code as comments is a good measure, but also remember that you may not revisit a module for years, and you will come to appreciate each and every breadcrumb you left which leads back to your original state of mind when you wrote it. If you measure code quality as maintainability, then comments can indeed increase code quality, just non-linearly.
- cbanek 8y agoHaving written safety critical code (and reviewed it) it is very useful. On the other hand, as soon as someone not safety minded gets their hands on it, trouble happens. Comments aren't updated (and there's no way to make sure they are checked, other than GREAT code reviews by the original authors, usually with at least two or three people doing critical reviews). Then the comments can become misleading and a liability as people will take them for truth, as they should. If you have code that has a lot of subtle dependencies or edge cases, really great comments can help enormously.
- beokop 8y agoNothing to do with ratio but I’ve found that the quality of the comments often reflect the quality of the code.
- majikandy 8y agoNo comments are good comments.
- newnewpdro 8y agoNo, I do not find it indicates quality. To me, comments are noise, and code is signal; the code is what actually executes. It's one thing to have a summary of intent at the start of a listing, that should not count towards the code:comments ratio. Once the code begins however, there should be a minimum of comments necessary - especially in a high-level language not constrained to assembly-level instructions. In assembly listings it was common to have two columns, the code on the left and comments which often resembled high-level pseudo code on the right. Here's some representative apollo guidance computer source: MAKEPRIO CAF ZERO TS COPINDEX TC LINUSCHR TCF HIPRIO # LINUS RETURN CA FLAGWRD4 MASK OCT20100 # IS PRIO IN ENDIDLE OR BUSY CCS A TCF PRIOBORT # YES, ABORT When you're already working in a high-level language like C or Golang, you should be able to clearly communicate what is going on without the need for littering it all with comments.
- geofft 8y agoWhy do you want to abort when prio is in endidle or busy, and not in other cases?
- Koshkin 8y agoExactly. True, code could be self-explanatory, but sometimes you need to explain why code does what it does.
- newnewpdro 8y agoIf you care to understand the code I pasted, here's the full listing: https://github.com/chrislgarry/Apollo-11/blob/master/Comanche055/DISPLAY_INTERFACE_ROUTINES.agc#L736 https://github.com/chrislgarry/Apollo-11/blob/master/Comanch...
- geofft 8y agoWell, the first 500-ish lines of that 1500-line file are comments, and there are block comments throughout, too... You did, to be fair, say that comments at the top shouldn't count. But I think that depends a lot on personal (and language) style towards multiple files and multiple units within a file - for instance, none of this code is object-oriented, and comments above each class make sense in an object-oriented language. I think as the language gets more concise - Go is a lot more concise than the Apollo assembly language - you're going to need to have the same amount of prose to explain what you're doing but a lot fewer lines of code to get anything done, and it makes sense to have comments above each function or each block, because that's really the comparable unit.
- josteink 8y ago> do other HNers also feel that a high comment:code ratio probably indicates quality? I consider it a big risk of errors. When some code is changed, will all related comments be rewritten too? I doubt it. And then you end up with a codebase which indicate A but comments which clearly spell out B, and you as a maintainer have no idea what to believe. DRY. Don’t repeat yourself. The comments should not double up for the code. That’s just future maintenance nightmare.
- macintux 8y agoShort functions help here. If every function is just a few lines long, the comments are easier to keep synchronized, and if a function drops out of service, it should eventually be garbage collected with its now-irrelevant comments.
- emn13 8y agoBut what if comments pertain to unexpected states the system as a whole can be in? Kind of the whole problem is when there are weird corner cases going on that straddle function boundaries. I'm not saying that's a good thing; mind you - but nor is it always trivially avoidable, especially if code needs to be concurrency and/or exception safe -- or in general whenever the statements your function consists of have surprising and opaque behavior based on system state, particularly if said state is hard to grasp due to being implicit or dynamic, or simply large and complex.
- macintux 8y agoAgreed, but that’s why I prefer writing code that has no global state. In Erlang, for example, it’s unusual (and the language lends itself via pattern matching to having short function clauses). It gets a little tiresome threading the relevant state to every function that needs it, but it’s worthwhile in the end.
- emn13 8y agoEven a pure function has "state" - namely its (arbitrarily complex) inputs. But sure, it's a little less of a landmine. The fundamental issue remains that sometimes your knowledge about that state (whether the classical kind or a proper parameter) can be complex and dependent on what happened elsewhere, especially if the codebase your in was grown into that situation, and not designed like that per-se. A comprehensible set of preconditions and postconditions isn't always a luxury you have, certainly not at first.
- kraftman 8y ago'A comment is a failure to express yourself in code. If you fail, then write a comment; but try not to fail.' - https://twitter.com/unclebobmartin/status/870311898545258497?lang=en https://twitter.com/unclebobmartin/status/870311898545258497... And a bit more on the same from clean code: http://www.kyleblaney.com/software-blog/2012/6/29/comments-are-a-failure.html http://www.kyleblaney.com/software-blog/2012/6/29/comments-a...
- geofft 8y agoHow do you successfully express "We need to treat all transactions on February 29 as happening on February 28, see customer ticket #4321 for rationale" in code?
- natalyarostova 8y agodef we_need_to_treat_all_transactions_on_february_29_as happening_on_February_28_see_customer_ticket_#4321_for rationale: obviously
- krapp 8y agoThe sad thing is, you're not entirely wrong...
- Kaveren 8y agoPerhaps a function to get the "true" transaction date given a transaction date, and explain the "why" by adding a special function describing the rationale in brief through its name.
- kraftman 8y agoBy naming as much as possible. I'd need to know the rationale in the ticket to be able to try and codify it, but here's how I'd try and do the rest: https://codepen.io/anon/pen/Jwyzdv https://codepen.io/anon/pen/Jwyzdv
- geofft 8y ago
- brandall10 8y agoThe comment:code ratio is similar to some legacy enterprise C/C++ systems I've worked on. I've been on Rails/React teams where comments were seen seen as a possible smell. Not talking about useless literal comments, just that their need was seen as pointing to possible bad design and that a well factored codebase was self-documenting -- ie. if you had to comment something, perhaps methods/vars were poorly named, SOLID principles were not adhered to, methods needed to be broken out, or it was just a sloppy approach. Even explaining design decisions was considered more in the domain of git messages and having nicely packaged atomic commits. While I see that aspect of it, there's no getting around the constraints of the real world and that some problems are just difficult and much easier to grok with a user guide in plain english, so to speak. And mission critical stuff needs as many safeguards as possible. That said, inaccurate comments can be dangerous and when your code is highly commented there is real danger things can get out of sync. If you're working on a 5000 line file that 100 developers have touched over a 20 year period... and no one has taken it upon themselves to do a recent comment audit, there be dragons.
- sitkack 8y agoI have worked on teams with this same attitude, and in my case it was just a systemic way for the group to rule-away having to write comments. The codebase suffered for it.
- fouc 8y agoProbably depends a lot on the programming language.
- wtroughton 8y agoThis. The code base should be the authoritative source of the behavior of the system. The comments should be the authoritative source of what is expected of the system.
- topmonk 8y agoI think repeating the same concept in different ways just makes things harder to read, not easier. Comments also sometimes reference code outside of where they are placed. This leads to them becoming misleading and incorrect. I find that comments can be a last ditch effort to make hacky convoluted code look better than it is. It can be an indication of lack of thought and planning and later obsessive documentation to make up for it.
- twunde 8y agoIt's really only useful in areas of codebases that either a) are very complex, b) touched by many people or c) both. When that happens, everyone prefers that there is a lot of documentation, especially about the why. With older codebases the question is always whether this is an actual bug from the developer or is there a reason why it's doing this super-weird thing and if so is it still applicable. What's happened over the last 5 years is that automated testing has become so mainstream that places without tests are the exception AND the tests have replaced the need for comments.
- TeMPOraL 8y agoYou've missed d) the codebase lives longer than a few months and someone else than the original author has to make changes. Comments describing the intent and caveats are extremely useful in ensuring the future developer gets adequate understanding quickly, and reduces the chance they'll introduce bugs. Tests can help understand the interface, but they don't help to understand the rationale behind it, the underlying abstraction, or implementation caveats.
- simplyluke 8y agoAgree 100%, along with accompanying documentation that lays out architecture, rationale, challenges, etc. All of those are invaluable for any code that will outlive the tenure of the developers who built it. And given how often people in tech change jobs that's virtually all code.
- TeMPOraL 8y agoOh yes. And even disregarding tenure, you have cases like illness (see e.g. the Word 1.0 postmortem[0], page 14, talking about losing a key developer), or people changing project. One time, I inherited a big steaming pile of spaghetti my co-worker wrote to meet a tight deadline, before being shifted to another project. That code implemented one of the key functions of the application, and half a year later, the customer demanded extensive changes. Believe me, I would have paid half my monthly salary the just to have a third of the comments that we see in this Kubernetes file. -- [0] - http://antitrust.slated.org/www.iowaconsumercase.org/011607/8000/PX08875.pdf http://antitrust.slated.org/www.iowaconsumercase.org/011607/...
- emn13 8y agoI think it's usually a sign of a poorly understood domain or a poorly modeled problem. It's not a good sign; it's not necessarily a bad sign; it's (at best) an admission of one's limitations. Comments become useful when behavior is implicitly tricky. Ideally you'd make the "trickiness" tangible and expressible in-whatever-language you're in, but that's not always easy to do.
- geofft 8y agoI generally find that a high comment to code ratio, if the comments are of the form "Do this thing because of this reason", indicates quality. It indicates the programmer both knows what they wrote and why they wrote it, and it helps future maintainers figure out under what circumstances the code can be changed, refactored, or removed and under what circumstances the original behavior must be kept. A high comment to code ratio, where the comments are of the form "Do this thing in this way," indicates a lack of quality - generally a sign that the programmer is not confident enough in the language that they're writing in, and is trying to solve language-level problems instead of business-level problems. Uncommented code better come with some reference for why the code exists in the form it does. Sometimes commit logs and the VCS "annotate"/"blame" feature works. Sometimes commit logs link to bug trackers or feature requests. Sometimes there's a README. If you don't have any of those, I tend to find that it's generally low-quality code. Our purpose is to deliver business value. (Or non-business value, as the case may be; if you're writing a free video game for fun, you want people to successfully have fun.) Our purpose is not to generate lines of code. All code is, to some extent, legacy code; comments can help it be manageable legacy code, or make it even more unmanageable.
- Karrot_Kream 8y agoThere's a lot of talk about comments becoming stale and code being self documenting in the replies which makes me wonder: do people genuinely not read comments and just made code changes without updating comments? And do reviewers not look at the context of the surrounding code and just let commits in? What's the point of having code reviews then?
- geofft 8y agoComments straddle this weird line between code and human process. They're in the source code files themselves, and there is an appeal to trying to evaluate a project by looking at the source code alone and trying to gauge abstract technical merit. But I think the real truth here is that comments are a tool in the service of a development process, which includes things like having code reviews, having code reviewers be sufficiently motivated (intrinsically or extrinsically) to care in useful ways and neither nitpicking nor rubber-stamping, having motivated people on the project in the first place, having shared values about what code you're going to write and what code you're not, having tests and doing the operational work to keep tests running, retaining people on the team, etc.
- TeMPOraL 8y agoI'd say it's mostly a meme. If a code review doesn't involve reviewing comments around the modified code, it's a bug in the process. Elsewhere in this thread Ousterhout's book is mentioned; I like his advice about always placing comments in the most obvious places and as close to the code they affect as possible. This way, you can't miss them, and and it's hard to forget to update them.
- lozenge 8y agoEveryone can have comment blindness to some extent, but I've worked with two people who auto-collapsed docstrings and didn't read and hence update comments, which is enough (one person writing code without updating comments/docstrings and one person inadequately reviewing). Sure, the problem only appears in a bit of the code, but it means people stop trusting all the comments.
- Jach 8y agoThe logical conclusion to more comments is Literate Programming. This book for instance is also a program: http://www.pbr-book.org/3ed-2018/contents.html http://www.pbr-book.org/3ed-2018/contents.html This file isn't that heavily commented. Do you look at many OSS projects for comparison? Though when things get complicated with many branches and function reentries it makes me wonder whether the problem would have been better solved with declarative logic that handles the procedural mess for you. (It might also be much higher quality since you may unlock access to various formal methods and go beyond unit tests. Though perhaps for example there's a vetted TLA+ spec not shown that this controller is based on.) I don't think doc'ing every function is unusual, usefully doing so is less common though. Comments in the function body also aren't that rare, though it might indicate a place for better factoring e.g. just more function calls on descriptive/suggestive names. (Having more functions will help in not having to stub out (and deeply stub) so much in a behavioral test, too, since you can get away with just mocking the function call instead of the potentially hairy state logic the function does underneath.) I see an example at a random spot for a couple improvements in naming (in my ignorant opinion, I don't know about kubernetes) -- though the fact I feel able to express even a weak opinion on an improvement suggests the comments were reasonable. I've seen code less hairy but with no comments or useful tests and without a need to really understand it I just want to move along pretending I saw nothing. Look at the set of ifs at L591. The first if is a null check with part of the explanation on L592, better to remove that part and have a function call, something like "claimWasDeleted(claim)". The matching else if on 615 checks for an empty string name, I'm not sure but I think its explanation is at L634 and the empty string check could be "isClaimPending(claim)", and maybe move the mode mismatch check to its own else if before the isClaimPending block and give it a better name. I appreciate the comment on L635 telling me why the next line of code on 641 is done (it may likely not be clear from the commit history, which can be another place for whys) though with the isClaimPending change the comment and code might be replaced with a fn call with the details in the fn doc. I'm also reminded of an idea in more expressive languages to annotate purely optimization metadata of any kind (inlining being the simplest) and being able to toggle it on/off for extra QA in a test suite. Anyway the next elif on 643 and its comment, could be something like "isVolumeBoundToClaimProperly(claim, volume)". You get the idea.
- protonimitate 8y ago>However, it does give me some comfort. When it’s not gamed, do other HNers also feel that a high comment:code ratio probably indicates quality? I think people should spend more time commenting/documenting across the board. I'd much rather have verbose commenting that is unhelpful that I can skip, versus minimal commenting and code that is overly optimized and hard to parse. The less thinking I have to do to pick up where the last person left off, the better. I would say that yes, in general high comment:code ratio tends to be higher quality.
- jcranmer 8y agoThe way I think about comments is that you should always be able to articulate what the consequences of deleting any line of code is. If the code itself is insufficient to do that, it needs a comment. There are three kinds of comments: why, what, and how. How comments are almost always a sign that the design is poor or the complexity is too clever. Why comments are necessary to understand the code and are almost always a good thing. What comments can be useful guideposts for skimming code, but they are also extremely prone to code rot. I suspect what comments generally end up being neutral in a net value proposition. You want a high ratio of why comments to code, but I suspect most high comment-to-code ratios arise from what comments, which severely attenuates the utility of a pure comment-to-code ratio.
- kansface 8y ago> When it’s not gamed, do other HNers also feel that a high comment:code ratio probably indicates quality? Just the opposite. It typically indicates a history of rigorously documenting terrible code. Sometimes, comments come from complex business requirements or other external constraint. Documenting the former is largely an anti-pattern while documenting the later is hugely useful.
- zorga 8y ago> do other HNers also feel that a high comment:code ratio probably indicates quality? Nope, imho code with lots of comments is generally crappy code. It's littered with comments to explain the sloppy code they couldn't make clear because they're bad programmers. Good programmers use few comments, write simple clear code that doesn't require explaining, and leave comments about why something was done rather than simply trying to explain what the code does. Code never lies, comments often do; don't trust comments that explain the code.
- vectorEQ 8y agoi would say like you say it depends on the quality of the comments documenting the code. if they are correct then it shows a thorough understanding of what is written in code, apart from that a complete stranger to the code can easily find what they need. however, like you said, you will need to maintain comments more than code, which is a pain and will lead to inconsistencies in the comments, leading to crappy file with meaningless junk scattered in it, which in turn means you can never trust comments, and it's therefore kind of useless to have. :d but since that's a circular argument, and those tend to be just cynical in nature, i do prefer properly commented code above uncommented code. i'd do it less verbosely myself so i don't need to maintain so much of it though, trying to keep it more consistent over time.
- AlexCoventry 8y ago> do other HNers also feel that a high comment:code ratio probably indicates quality? That's always been my instinct.