26 ms·
Reducing technical debt by valuing comments as much as code
- twiddling 4y agoHaving done some "code archaeology" in my past, I loved coming across a good comment block, with clear rationale as to why something was done, which looked incorrect if you only had the code.
- MSFT_Edging 4y agoI always write comments, even on code I've written myself it comes in handy. 6 months later I wont remember why the "easy" solution wasn't the path that was taken, or some complexity that needed special handling in a single case that was discovered through a few hours of debugging. Sure you could write perfect code, but writing out your thought process helps tremendously with understanding a thought process and getting up to speed far faster.
- alyandon 4y agoSame - if my code is complex enough to not be easily written in a few lines I'll drop a comment about what it is doing and maybe even why. It takes a minimal amount of effort while I'm coding and saves a lot of time when I (or someone completely unfamiliar with the code) have to revisit it months/years later. My guiding principle is that I don't want someone to read my code years later, exclaim "Who the hell is this alyandon guy?!?!" and be motivated enough to create a time machine so they can go back in time and smash my keyboard to bits before I wrote said code.
- collyw 4y agoLikewise if I am using some advanced feature of the language / framework, I think it's worth a comment.
- still_grokking 4y agoI'm arguing here all over the place for writing comments. But exactly this kind of comment mentioned here I think is the most useless sort of. Someone working on the code should know the language. If they stumble over something they don't know they should read the documentation of the language. Explaining the programming language you use in code comments is a terrible idea, imho. It's like writing comments of the form "adding the numbers" and than adding some numbers. Just useless noise. The more important question would be, as always, why you used this feature? What would be e.g. the alternatives? Just stating that you do something, just to do it than with code makes no sense. Nobody needs that redundancy.
- collyw 4y agoHow can people ever learn new languages if they are expected to only work on languages that they know? There are loads of systems out there using multiple languages. I agree why is more important than what. But sometimes you run into some strange functional construct that is very clever, but not in the slightest bit intuitive to read.
- still_grokking 4y agoIf something is not intuitive to read this is bad code most likely. If there are good reasons WHY this is still the best way to do things, this WHY should be explained. But, of course, not the how. It's self evident that some "special" functionality was used. If you read some scientific paper you would also not expect to find there basic explanations of the scientific topic. To read and understand a paper you need to know the subject. The same goes for code: You need to know your tools. Otherwise you can't use them properly anyway. Language documentation just does not belong in random code comments. The comments should be there to explain your special use case, not give some basic tutorial to people that don't know the tool used in the first place. That are completely different concerns, and should not be mixed therefore.
- deleted 4y ago[deleted]
- clnq 4y agoI agree. Over years, I have saved probably many hundreds of hours explaining the systems I own to new engineers on the team by maintaining good code comments. It also helps prevent bugs as sometimes people might change code without understanding it well, but comments mostly make that impossible. It is difficult for me to understand why the debate surrounding code comments is so heated. I had some strong opinions about these things when I was very new to engineering but I rarely see anyone senior doubt the effectiveness of code comments. I get the idea of self-documenting code, but very few things are self-documenting to a new person on the team that never worked with your massive proprietary codebase. They need a lot more context. I would like to see some examples of self-documenting codebases. Sadly, people like Uncle Bob who loudly hate code comments tend to have codebases that are not very self-documenting. Perhaps not writing any code comments is an interesting exercise, but I think it might work much better in small siloed projects than in companies where hundreds of people have to collaborate on the same code and not introduce defects. I wonder if this is where the disagreement about things like code comments comes from - different circumstances of the programmers.
- midoridensha 4y ago>Perhaps not writing any code comments is an interesting exercise It's an interesting exercise very similar to the infamous Perl one-liners from the 2000s. >but I think it might work much better in small siloed projects The problem here is that those "small, siloed" projects frequently get out of their silos and become bigger and more important than originally envisioned. Then all the new people looking at it have no idea what it's doing.
- wpietri 4y ago> some complexity that needed special handling in a single case Shouldn't that be expressed in a test? To me, "there's a special case that drives the code in a particular direction" is Exhibit A for "things that belong in tests".
- specialist 4y agoExactly. I don't remember what I had for breakfast, much less some brain fart I had 6 months ago. As a kid, I somehow got the impression that Microsoft had a coding standard for 1:1 comments to code. So I thought I'd give it a try. (I had a lot of free time.) For the 1.x to 2.x version bump of my text editor, I meticulously went thru and commented everything. (I also switched to 1 statement per line guideline.) The outcome was awesome. By requiring a comment, any comment, for every statement, it evolved into a form of story telling. I wasn't just explaining obvious stuff. It helped tremendously with future maintenance. Alas, I've never repeated that experience. I'm not entirely sure why. It's a bit like Knuth style literate programming or TDD. Some kind of Platonic ideal. An esthetic ideal to strive for, but not very practical.
- davidw 4y agoI worked with some Rails folks a while back who were utterly convinced that comments were to be avoided because it meant your code was not clear. I agree that comments explaining 'what' is happening are mostly useless. Write clearer code. But 'why' comments are good. Most things can be coded up different ways. Tell me why you chose this way. Tell me about constraints that might not be immediately obvious. Let me know if indeed, it could be cleaner, but you were in a hurry (this is a thing that happens in the real world), or if it's that way for a specific reason.
- JohnBooty 4y agoI worked with some Rails folks a while back who were utterly convinced that comments were to be avoided because it meant your code was not clear. One of the few things that makes me want to reach a management position is my burning desire to alter this widespread, toxic, and absolutely bizarre belief. As an IC, even a senior IC, it's difficult to effect this change.
- paulddraper 4y agoWhat question will the next engineer have about your choice? 1. Rewrite your code to make the answer obvious. 2. If that's not possible use a comment.
- layer8 4y ago3. Be aware that programmers tend to be bad at judging what is “obvious” about their code.
- kawsper 4y agoArkency, a very well-known Ruby consulting company (at least in Europe), are the ones I've seen shout about this 'rule' the loudest: https://twitter.com/arkency/status/1254784379190038534 https://twitter.com/arkency/status/1254784379190038534
- latchkey 4y agoMy time at Pivotal Labs was similar. "The tests are the documentation!"
- catskul2 4y agoI feel statements like: "...team leads (and managers) allow comments to get out of sync with the code..." reveal a fundamental misunderstanding of how software organizations generally work.
- doctor_eval 4y ago> Because the culture of many development organizations undervalues comments, team leads (and managers) allow comments to get out of sync with the code—thereby increasing technical debt instead of reducing it. Comment bit rot is inevitable, because comments don’t compile and can’t be tested. The only way to keep them in sync is by hand, which takes a lot of time and energy and is far from perfect. Of course, > The first problem is that most developers are under great time pressure and don’t have the time to make the code so utterly clear that it requires no further comment. So they don’t have time to write the code clearly, but they somehow magically have time to read and review all the comments and to keep them in sync with the code? And the reviewers too? “If only developers worked harder…”. It’s nonsense. Comments are great, they have an important place in software engineering, and I always regret when I forget to write some in a file or class. But they are not a silver bullet, and must be treated with suspicion, because there is no way to prove if they actually describe what’s going on. And that’s the same reason that they are hard to keep in sync.
- jonfw 4y agoGreat thing about Git, is you can look at the code at the time when the comment was written, and still retain the original value of the comment. If there have been major structural changes that make the comment useless- that’d be pretty easy to see, it’s very easy to delete comments
- pmoleri 4y agoThis, I prefer an inconsistent comment that can still shred light on some code than no comment at all. Code also becomes obsolete and no comment just makes it worse.
- wombatpm 4y agoComments in code are like pizza or sex. When they are good, it’s really good. When it’s bad, it’s better than nothing
- makeitdouble 4y ago
- simonbarker87 4y agoI’ve always pushed back against the “no comments, they go out of date” sentiment. Comments aren’t milk, they don’t just go off, developers let them go out of date. As others have said, comments should be used to add why, to give context.
- randomdata 4y ago'Why' should be documented in your test suite. Leave a comment too, but don't think you can skip out on the former because you've done the latter.
- citrin_ru 4y agoTests can show what code is expected to do from the point of view of the tests author. They usually have no information why code works this way. Also I've seen more than a few times tests which ossify wrong behavior. Tests need comments too.
- randomdata 4y ago> They usually have no information why code works this way They need to if the the way it works is significant. If it is not significant then the value of a comment becomes somewhat dubious anyway as the code is expendable and doesn't really matter. It is not necessary to understand the program and if it is flawed you're going to rewrite it. Comments can add a lot of value, but there is a line where the value quickly diminishes.
- still_grokking 4y agoHow does a test inform you why a function was implemented using algorithm A and not algorithm B which would also do the same? And no matter how clear and clean you write algorithm A, the code will never answer the question why this algo and not another was used. That's the meaning of why here.
- 4y ago
- exabrial 4y agoUnpopular opinion, but in the words of Linus, I have my asbestos underwear on so flame away: * Comments are excuses * They're used to validate the existence of crappy code * They do nothing for you in production Instead: * we commit to writing log messages... which are sort of like comments, but they work in production
- dbrueck 4y agoCode captures only a portion of the thinking that went into the software's design. If you don't preserve the rest of that thinking elsewhere, you're forcing people to recreate / rediscover it later - and probably the most common way to do that is to throw away the code and rewrite it. So-called "level of intent" comments as well as comments highlighting tradeoffs, gotchas, flaws, limits, exceptions, assumptions, and so on, are incredibly valuable if you preserve them alongside the code. Comments explaining why this function exists and what it's for can help you quickly come up to speed on a new code base - this is especially helpful when it comes to handing off code to a new owner or expanding the team of owners. The following code may or may not be well written (who can say??) but it's not exactly inviting new contributors: https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/motion_est.c#L109 https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/moti... Around the time of writing the code, comment-free code looks clear to the author because they have the benefit of all of the thinking that went into writing the code. I'd argue that in production is when comments are often most valuable. The middle of a crisis is a terrible time to wonder what assumptions were made when writing code a specific way, or if a certain line of code that seems to be doing something weird really is weird or if it was based on something you're not considering. It's also the time when you want to maximize the number of people that can jump in and help. Everybody has their own coding standards and there is certainly some subjectivity to those standards. Here's mine for people who work for me: if you don't document your code, you have no business touching anything that goes anywhere near production, you can't do anything that is critical path, and you should make a sincere effort to change or start looking for another job. :)
- still_grokking 4y agoI agree with everything said. But I need to point out: The code sample is just hilarious! Typical C code… Not even correctly indented. ;-) I will never get those people creating all this write only code. The C hackers seem to even think chars in symbols are scarce, so they still name them like `c`, `d`, `s`, `pp`, `me`, `mv`, `qpel`, `fx`, `bx`, etc. Paired with zero abstraction (because C is not much more than a macro assembler) this creates the most horrible code I can imagine.
- majikandy 4y agoI love seeing comments in the code as they are usually the best entertainment I get all day. Especially when the code below it pretty much doesn’t do what it says anymore.
- swatcoder 4y agoComments are critical to long term project quality and consistency, but they're always going to rot until tooling starts taking them seriously. For instance, it's great that code reviews have become standard practice at most organizations and for many projects, but the tooling for those reviews almost always rely on showing the few lines above and below a code diff. The reviewer has no convenient way of seeing how the changed code may conflict with any applicable comments unless the comments happen to be within those few nearby lines or the diff happens to include comment changes. Even then, the big picture is out of view and rot is still likely to seep in. It would be nice if incoming developer-support AI could start tackling this, by surfacing impacted comments and even "linting" them for applicability and accuracy.
- cma 4y agoMayhe something like chatGPT could be fed diffs of a change and warn about comment rot and recommend fixes (once it has a much bigger context window).
- alexisread 4y agoEven better if the language supports scoping comments to particular code blocks, and comments can be made in markdown/mermaid (or equivalent) so you can diagram, link and TODO comments. Documentation tooling should be able to make a good job of constructing a class/function DAG with scoped commentary. This is kind of a reversal of Literal documentation, but I suspect it may be more maintainable by teams. Literal docs only seem to go in one direction, that is documentation->code, not the other way around. This I guess is more in-line with scientific hypotheses. Literal tests may be even more tricky as TDD doesn't gel well with Literal hypotheses. I guess a Doc-driven dev process would be a novel approach here, and probably more usable than AI-supported systems. Copilot has been quite divisive on it's effectiveness. DDD in that every eg. Class requires a comment and a test even if they are blank, to force at least a thought about them. Having a code manifest at the root of a repo can also be used to configure the envs the code runs in, and the integration tests that it needs to do both local and in-place. Lastly, as mentioned elsewhere, logs are comments as well, and again would be well to be scoped in the language.
- still_grokking 4y ago
- zabzonk 4y agoi think comments can be very useful. for example, look at the c function strlen: int strlen( char * s ); the following comment pretty much describes what it does: - if passed a null-terminated string, returns the number of characters in the string, excluding the terminator - if passed a null pointer, or an incorrectly terminated string, behaviour is undefined these are the kind of comments i like to see
- ternaryoperator 4y agoThe link at the end of the article to the JVM written in Go is a cool project. The GH project is at https://github.com/platypusguy/jacobin https://github.com/platypusguy/jacobin
- revskill 4y agoIt's time to get comment generated via toolings.
- ChrisMarshallNY 4y agoI have come to a "middle ground," when structuring and commenting code. First, the code needs to be fairly clear, but not "stupid" clear. I have had people tell me not to use idiomatic Swift, because "a JavaScript programmer can't understand it." In some cases, this may be necessary, but not in mine. The #1 consumer of my code, is Yours Truly. The wonkiness doesn't bother me, but sometimes, I may not be aware of why I did something (that may not be "idiomatic," at all). That's why I may write a quick comment, like so: showThrobber() // The reason for this, is that we need to give the throbber time to show up. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(20)) { That explains the awkward use of an "asyncAfter()" method. It was the result of me, wasting a good half hour, trying to figure out why the screen didn't change. I saved future me, a half hour (and also a signpost for "improvements needed"). I write about my approach to documentation, here: https://littlegreenviper.com/miscellany/leaving-a-legacy/ https://littlegreenviper.com/miscellany/leaving-a-legacy/
- still_grokking 4y agoAlmost perfect. Only most people don't read code bottom to top… ;-) When reading this I didn't understand the comment at first, before I realized that it's meant to say something about the following line. It would be better therefore to write it like: showThrobber() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(20)) { // The reason for this, is that we need to give the throbber time to show up.
- ChrisMarshallNY 4y agoGood point. Thanks!
- runald 4y agoI'm going to disagree with you there. It's a convention that comments refer to the following lines of code, not above. Reading from top to bottom or bottom to top has nothing to do with this. A better way IMO is to disambiguate what specifically "this" refers to in the comment.
- smeagull 4y agoI think the real way you can reduce technical debt is by valuing code less, not comments more. Comments are vital, but I prefer everything be refactored to make the code the comments, which only happens if you get naming right, the language, libraries and the frameworks don't fight you. Which is a lot of ifs. Even then you need the comments to label parts of code that are exceptions to normal practice, or to fix particularly subtle bugs so that you prevent regressions from happening. (If you want tests to do that, it doesn't obviate the need for comments - you probably want the comments in the code and the test, because you don't want it to be standard practice when you are editing code to discover a new all the failing test cases when you make a change)
- tippytippytango 4y agoIt would be really nice if there was any data this article could could cite, pro or anti comment to see if it makes any measurable difference to your team’s market competitiveness. The data they cite on TODO items isn’t relevant as the experiment lacks any controls and is thus non-scientific. The best we can do given the dearth of data is consult the market for answers. There are successful software companies/projects/individuals that subscribe to either philosophy (sometimes simultaneously) and the market doesn’t seem to care as it does about how good the product actually is. Stuff like this is bike shedding at best, at worst it’s a kind of virtue signaling to some group in an attempt to appear as a blessed expert.
- pron 4y agoWhat you say is true, but then again very little on the cost side of programming has a big bottom-line impact because software is such a high margin industry. So this topic, like many others in software, is largely a matter of personal taste, but that's not to say all opinions are equally distributed among programmers. If most programmers find it more pleasant to read code with good comments, then writing them is a nice courtesy.
- amelius 4y agoCan't we generate the comments using something like GPT3?
- CaptainFever 4y agoI like writing comments like I am writing for Copilot (even though I'm not using Copilot). It forces me to write better and clearer comments.
- bonestamp2 4y agoClear code makes the What and How obvious. Good comments and commit messages explain Why.
- kazinator 4y agoDetailed commit messages should document most of your coding decisions, not comments.
- kderbyma 4y agoComments are vital. good comments are a multiplier. I have never been put off because of comments except when there is a wall of text explaining the entire file.....no...just no.
- _madmax_ 4y agoCutting all comments under the false certitude that if code is clear you shouldn't need any is as dogmatic as leaving a class comment explaining the whole file whether you needed it or not. Stop being so dogmatic about comments and do what works for your team. Such a flame war territory.
- hakunin 4y agoSeems like an appropriate time to share my 4 reasons to leave a code comment: 1. An odd business requirement (share the origin story) 2. It took research (summarize with links) 3. Multiple options were considered (justify decision) 4. Question in a code review (answer in a comment)
- spoiler 4y agoI've not been doing 4, but it's s great idea. If someone's asked the question, it's likely it will come up again for the next person reading the code!
- capableweb 4y agoAs an aside, my first try is always to try to clarify the code itself if someone has a specific question, so the obvious answer is in the code. But if I'm unable to signal that in code, a comment will do just fine.
- hakunin 4y agoI couldn't fit this part in my tweet, but this is an important caveat.
- breck 4y agoGood list. I would add: 5. todos
- pmoleri 4y ago2. Is very applicable to workarounds often linked to 3rd party issues.
- gremlinsinc 4y agoThese are almost exactly my own reasons, except I have #5 - annotations as needed for some php frameworks, and especially for ide intellisense. E.g. if the ide can't grok what a $var is you can do : /** @var Some\Namespace\To\Class $var */ $var = ... then when it reindexes things it has no problem tying everything together.
- spoiler 4y agoI generally tend to think of code as "encoding" or formalising intent. If the intent is obvious from the code comments are usually not necessary, but if the intent is hard to decode when glancing at the code, then I comment on it. Sometimes things are just complicated and they require explaining the intent to help the reader understand the code. It also helps spot bugs or allows someone smarter than me to rewrite it in a better way (for different axes of better) There are other situations where comments are useful that are covered elsewhere in the thread, too. So, I've gotten some good ideas on how to improve my code comment etiquette!
- bottlepalm 4y agoLoving all the pro-comment comments - way to go Hacker News! We’ve come a long way since the days of everyone posting that static typing is the devil, and that my code ‘documents itself’.
- midoridensha 4y agoYeah, now only 50-75% of the comments here are anti-comment. I'm not sure that's a huge help, but I guess every little big counts.
- raitucarp 4y agoNow, we can delegate such tasks, comment every functions, classes and variables to GPT-3 davinci or Codex with clever prompt as clear as possible, (ELI5, reasoning, anecdote, storytelling, metaphors, etc). I think that would definitely useful AI use case.
- twobitshifter 4y agoI don’t know how many people have worked on a project with JavaDoc, but it really is an incredible boon, as the OP notes, and will make you want to comment everything with quality. People talk about “poorly documented code”, which thy acknowledge is a weakness, but they don’t connect that the comments cover the documentation. If you’ve ever joined a place with turnover, having you own documentation on the magic mega project is really valuable. Yes, comments can lie, but you’ll figure it out when the call doesn’t do what it says on the box. The benefit is that you jump ahead on all cases where the comments are truthful and the code still works without issue. You might also discover that someone already written a method or tool you thought you needed. There’s huge savings from having comments and documentation. Comment and documentation can even be a way out of the bus problem.
- keithnz 4y agoMore generally... my unwritten article is "Reducing developing bad beliefs about code by not listening to Uncle Bob". He has been trying to say profound things for a long time now. He was super active in the XP community in early 2k onwards and he was nearly always saying things that I felt were a bit "off". i.e. there was a gem of an idea, but the idea was turned into some principle or rule that lacked nuance and context. Reality is, there isn't any fundamental rules/principles... just ideas, some ideas seem more universal than others, but these ideas are just a bunch of strategies you can use when approaching software development and depending on context they may or may not be good strategies. In terms of commenting, some of this weird "wisdom" around commenting was fundamentally rooted in the idea you can't fix bad code with comments. People noticed that a lot of times where there was comments in "poor" code it actually was a spot where you could do some kind of refactoring to make the code clearer. Eventually this morphed into "If you need to comment your code you have failed" type sayings. However, there was plenty of people advocating commenting to explain things the code can't tell you, but too many were swayed by "commenting is failure to write good code" that they threw out some of the reason why people like to put comments in. Many in their first 10 years of coding really want guidelines and rules and principles and argue strongly for things they have found effective compared to how they approached coding previously. But these things you learn are almost never universal, even if you can see/argue how you could apply it to all kinds of things, other approaches might actually work better, or might work better in different contexts.
- jalino23 4y ago100% agree with this. I was religiously following clean code but never really saw benefits. Nowadays I start by making code work and only abstract/refactor if it feels right. And I don't know how to articulate "feels right" but what I can say is a lot of times, the resulting refactor is the opposite of what uncle bob recommends.
- hakunin 4y ago> he was nearly always saying things that I felt were a bit "off" One of such things is "screaming architecture". It is a good idea in theory, but only if you already know what the architecture should be. Most new projects don't know what they need up front, and discovery happens over time. Screaming architecture is bad for this process. It inhibits it, requiring a ton of refactoring because of early assumptions. One thing that is known up front is entry points. (CLI, requests, tests, bg jobs). They're a lot more likely to stay around forever. Custom architecture should emerge underneath them. I guess we can call it whispering architecture.
- wkdneidbwf 4y agoi think what gets missed is that it depends. there are languages and domains where it is possible to write sufficiently succinctly and clearly that you don’t need comments. there are also places where you might want to explain the “why” even if the code is clear. relying on comments to understand the “how” has been a smell in every codebase i’ve seen.
- ehnto 4y agoThe Code as Documentation crowd produce beautiful code, and I follow much of the practice, but while it is good at self-documenting what is happening, it's hard to get the why entirely into code without being obtuse. Especially when working around framework limitations. This becomes very important in the maintenance phase. I can see you getProductCollection, I know what that does, but why do you do nothing with it? Oh it's because it needs to be loaded before presenting the cart, and there's a bug in the framework that fails to do so in this scenario. Also business requirements can be reaaally asinine, a makeThisParticularButtonGreenSeeMeetingNotes20122023() would be pretty lame but that is often required information for a developer revisiting a feature and wondering if something was a bug or intended.
- kyelewis 4y agoThis feels like somewhere that GPT could actually prove helpful- I don't love GitHub CoPilot all that much, but a linter that could warn and suggest where comments aren't matching the code could be helpful to keep 'comment rot' at bay
- feoren 4y agoIf they can do that, why ever have those comments in the first place? Just have CoPilot write the comments for you! It should be easier than having it read the poorly-written comments laden with shitty attempts at dry humor and mistyped abbreviations that most programmers leave around. Just ask CoPilot to explain the code to you. Have it hold your hand and walk you through what a for loop does, if you must. It'll be perfect for those programmers who used Chat GPT to get passing grades in their classes!
- pipeline_peak 4y agoWell defined identifiers don’t need comments
- r00fus 4y agoAs someone who took ownership of a large codebase from a genius former colleague who rarely explained himself, the only reason we kept the code was my insistence on replacing cryptic code 1-liners with easier to read/maintain multi-line expressions that had terse-but-readable variable names and //inline comments. The team ended up expanding the codebase quite a bit before that technology stack was retired a couple years later. Not sure if it would have survived without that refactoring.
- voidhorse 4y agoSome of the aphorisms and cheap philosophies people apply to programming are so contrary to common sense it makes me wonder how they got into the business of writing programs to begin with. Writing code without comments is like writing a novel with no exposition. Writing code with too many comments is like writing a novel that is all exposition. Aristotle remains correct in the world of software insofar as moderation is still key. You want just enough exposition so that your reader knows what the hell is going on and not so much that they get bored.
- mshanu 4y agoThere is a difference between you writing code for library and general purpose app. When you write code for an app, you are bound to change the code frequently than you are writing code for library, so while I think there could be merit in putting comments for library, i dont think it will counter productive to write comment for your app code, as it is pain in the wrong side to keep both code and comment consistent
- tablespoon 4y ago> When you write code for an app, you are bound to change the code frequently than you are writing code for library, so while I think there could be merit in putting comments for library, i dont think it will counter productive to write comment for your app code, as it is pain in the wrong side to keep both code and comment consistent So? Good comments are valuable, even if they aren't always kept absolutely consistent with the code. Comments shouldn't restate what the code says, they should either say things the code can't say (like why), or (sometimes) summarize what the code does at a different level detail to make it easier to understand. The trick is to read code and comments together, and dig into source history when something seems off.
- osigurdson 4y agoFor fun, I asked ChatGPT to write code documentation for a small sample class (C# xml docs in this case). It did an incredibly good job at this. I don't really think this type of documentation will be necessary in the future as it can easily be inferred by AI. I think that extends to code comments as well. Perhaps it is too early for such guidance but I suspect over time the pendulum will swing to not documenting / commenting any code which can be inferred from the code itself (even if the code would require considerable concentration to understand). Of course, it is impossible to infer from the code why something was done so this will always be needed.
- m463 4y agoLarge codebases are always a puzzle. Maybe I should be more plain - large existing codebases usually suck. I suspect they drag down engineers, and cause them to refactor, or burn out. But what if something like chatgpt could explain the code to you. If you could ask questions "does anyone call this function?" "who calls it, and what do they do with the results?" "can you call it a million times, fuzz the inputs and see if it crashes?" "can you replace the bubble sort with qsort?"
- zerodensity 4y agoThe only thing that can potentially make less technical dept is code reviews eg forcing multiple people to look at every new piece of code preferably also have automated tests and CI. The code can have comments or not, it's more of a preference.
- ac50hz 4y agoMost programmers I’ve worked with can write some code within minutes of a discussion but stall when they’re asked to comment or to vocalise what they’re doing and why. They believe the reason is that they are working at such an abstract level that it’s not easy to put into words until some higher-level concepts have been coded. Of course, at that stage, comments are not added either. Discussing the code for commenting at this stage often elicits a response which results in throwaway comments or another writer’s block. Everyone loses. My personal solution has been to approach code documentation as programming in one’s native language, or as is often done, in English. Learning to comment is given the same importance as learning to code. Comment maintenance is given the same priority as code maintenance. Explaining the actual function and expectations by comment is the essential part of writing code that expresses the functionality. Comments are given similar weight as code. Comment design is considered at an early stage. And comment maintenance is equally as important as code maintenance. Why do we talk about coding rockstars but don’t we talk about commenting rockstars? This isn’t anti-agile or anti any methodology if it’s presented as an integral and essential part of the task. Often, when mentoring such processes, the act of commenting liberates insights that may have only appeared during failed product testing. Of course, learning to comment effectively is learning to communicate effectively. Metrics for effectiveness are often elusive and people are rarely paid for lines-of-comments, so this is always a hard sell, unless it’s understandable to be a core coding activity. We see the same thing in related areas, like logging. Unless you need to solve a problem with the help of accurate logging data, you don’t see the need or utility of logging anything. As with comments and code, logging also needs consideration and maintenance. Learn to code Learn to comment Learn to log These mantra won’t come from above, so need to be learned and understood.
- makeitdouble 4y agoI heard an interesting take, making a parralel between comments and user manuals. User manuals used to be pretty extensive, and filled with information not just on how the devices work, how they should be maintained, but also on what mindset these devices were built and the general context. For instance I remember buying a vintage camera with the original manual, and it basically explained photography to beginners, including framing the subject, lighting, and shutter discipline. Nowadays a smartphone comes with 2 pages of instructions on how to start the device. Are we much worse because of that ? I'm not sure, something has been lost, but I also can't imagine a smartphone coming with 200 pages of explanations and addenda sent by mail on every OS revision. A code that is regularly evolving in significant ways is to me way closer to a smartphone than a vintage camera.
- cjfd 4y agoUsed sparingly comments can be very good. One should comment non-obvious things or gotchas. Where it goes completely of the rails is when programmers are forced to write comments in mandated places. One ends up with a code base where half of the code consists of comments that point out the absolute obvious. DatabaseConnection connnection; // Connection to the database. // Write a log line when the system is intialized logger.info("The system was initialized successfully."); When I see such comments I am severely tempted to conclude that if one is going to have a policy on comments forbidding them would do less harm then mandating them everywhere.
- hknmtt 4y agoI was frantic code commenter in my youth because I wanted to give as much information to other people as possible but as I became SR developer I dropped them altogether. Especially after I moved into Go. Nowadays, I comment only in two situations: 1. if it is important to explain WHY something is done in a way it is done 2. if there is some related or directly connected code far away that the person might miss or cannot know about and how this code influences it. Writing self-explanatory code nowadays is a standard. An era of newbie spaghetti code is long gone so no need to explain the code itself.
- EVa5I7bHFq9mnYK 4y agoI found that higher-level comments (docs), explaining the overall logic, design choices and use cases are often missing. Developers should be given time to write those.
- ajuc 4y agoThe article misses the most effective comments - git commit messages. Regular comments are subject to bit rot - they get less true with time. Unless actively maintained - eventually all comments lie. Git commit messages maintain themselves. If a line of code was changed - the git blame annotation will change. So you know exactly what the context was and exactly which lines the comment relates to. It provides context (you can see in the commit what else changed with it), and if you include the JIRA task number and a short description - it provides the WHY. IMHO the most important skill for writing understandable code is splitting the commits into sensible pieces and writing good commit messages.
- farresito 4y agoIn my experience, git commit messages are the least useful, because people never look at them, at least in the teams I have been part of. If something is important, it should be right there next to the code. One shouldn't have to `git blame` constantly. The more friction there is, the worse in my opinion. Another issue is that once you start refactoring code `git blame`-ing becomes harder.
- ajuc 4y agoThe friction is 2 clicks (right-click + show git annotations). And you can leave it open, it's just a small thin strip near the code. I always check git blame before committing a new code, because I've had this exact experience several times: - investigate a bug - find the responsible line with obviously wrong code (often it's even nicely commented and the comments and the code are contradictory) - fix the obviously wrong code - commit - 10 other bugs caused by your fix - git blame - turns out the "obviously wrong" line was there on purpose and your fix effectively removed a previous change - which you would know if you checked the git blame for that line - comments were lying because somebody did a refactor and didn't noticed 4 lines above there's a whole paragraph of what now became lies This is Chesterton's Fence rule of programming. Before you change a line of code - be sure to understand why it was there. Git blame is the best tool for that. BTW there's a similar rule for comments - when you change a line of code in some function - you have to check all the callers of that function (and their callers, etc.) to see if there were any comments near the callers talking about the part that you changed. THAT is the thing that nobody does in practice, and THAT's the reason why comments eventually lie.
- imtemplain 4y ago[dead]