6 ms·
Don't Comment Your Code - Write Better Code
- mrleinad 13y agoOr better use (and develop) a good judgement on where it's better to add some comment here and there if required. It doesn't need to be black or white. There are lots of gray in between.
- spoiledtechie 13y agoDon't listen to this guy. Comment your code, because if its in production, your most likely not be the only hands that touch it! Someone down the line will have to review it, change it or modify it. It saves both time and effort, if you comment the code. Just do it.
- lmm 13y agoWrite code that other people can review, change or modify. If you're coding right, comments should rarely be necessary for that (and indeed would often just be a distraction).
- IanCal 13y ago> Just do it. Seconded. I've got an algorithm here, and the comments are very helpful. In one place, an array is iterated over backwards which is important and would trigger a few edge cases if it wasn't the case. A quick comment to explain why it's being done makes it easier to read and less likely someone will change it without understanding the consequences.
- MetaCosm 13y agoOr, you know tests. Having a "defensive" comment (explaining some critical corner case) is just terrible, write a test that exposes it so code can be refactored. "WARNING" comments are a really bad thing.
- IanCal 13y agoOr, you know, both. Why not leave a comment explaining why a non-obvious code block was written. It's not an either-or situation. I've left a before because of a subtle GC bug triggered only on particular hardware, which could not be replicated in the development environment, and would only be revealed by a particular coincidence in timings. How do you test that?
- lawn 13y agoOr they will simply change or modify the code and leave the comment? Now the comment doesn't help, it's actually detrimental.
- dllthomas 13y agoPerhaps testable comments?
- jdbernard 13y agoWhy should we keep adding more complexity overhead to our languages and toolkits instead of finding people we can trust to do the job right?
- dllthomas 13y agoBecause there is no one we can trust to always do the job right, and so a large code base will accumulate cruft over time. Just how carefully do you search out any possible comment referencing code you change? It's not always going to be adjacent.
- jdbernard 13y agoThat's true, but at some point you cannot automate quality craftsmanship. Making comments part of the automated compile/test process in my opinion crosses the line and would be more detrimental than helpful. In this specific case I would prefer to add code review and emphasize practices like adjacency of comments to code. Code should be reviewed on a regular basis as well. We all make mistakes, but I think a habit of putting at least two eyes on it and of coming back periodically to review past work is better.
- dllthomas 13y agoI don't pretend to know it's a good idea, and there's undoubtedly poor ways to implement it, but I think it's worth exploring. Adjacency of comments to code helps, but not everything can be adjacent to everything else, and when necessarily disparate code necessarily interacts it merits a comment that cannot be local to both. Putting multiple eyes on the code is great, but 1) isn't prevented by what I propose, 2) isn't going to be perfect (and can perhaps be done more effectively with fewer things to have to check), and 3) sometimes isn't possible (if someone is working alone, for instance). As John Carmack recently put it, on a large project "[e]verything that is syntactically legal that the compiler will accept will eventually wind up in your codebase."
- ZeroGravitas 13y agoBut some people won't read the comments. Or the article.
- pachydermic 13y agoYeah, but I think his example of good code was pretty confusing. I still think it's a good idea to section off your code into smaller modules - each module should complete one 'step' of the process (whatever that means for your particular program) - and each module should have a short comment at the begging of the section explaining what it's inputs/outputs are or generally why it's there. Some comments for exceptionally tricky stuff isn't a bad idea, but like other people said they are often ignored and might get out of sync with the code that's actually there. But I still think some comments are better than absolutely no comments...
- koblenski 13y agoSorry for the confusing code. I took a look back at it after reading some of the comments here, and I found that I or Blogger had mangled the post. Almost half of it was missing right out of the middle. It's updated now, so hopefully it makes more sense.
- vidarh 13y agoAnd this is how we end up with comments that documents what the code used to do ten revisions ago.
- dkuntz2 13y agoYou must be doing comments wrong. If they explain the why, they should still be relevant. Or people should rewrite them when they adjust the code...
- vidarh 13y agoIf they explain the why, they may be justified, but they will still eventually become invalid when the code is changed to do something with a different rationale. And yes, people should rewrite them when they adjust the code, but like so many other things: In any reasonably large code base it sooner or later gets neglected because the code still runs and passes all tests without it. If you want "documentation" that will stay up to date, you either need an extremely rigorous development process, which pretty much nobody has, or your documentation needs to be in the form of test cases that will break when the documentation is no longer valid. I 30+ years of writing code, I've don't think I've ever come across a project of any reasonable size that haven't had substantial comments that were outdated. I would love to see such a beast - it'd be a little bit like encountering a unicorn.
- talmand 13y agoIf one cannot be bothered to update corresponding comments when updating code then I suppose they'll have problems updating the separated documentation as well.
- nakedrobot2 13y agono code will say WHY you did something the way you did it. only comments can do that.
- mrtbld 13y agoThat's right, and I think that was the point of the author: > I may put a few words in a comment to explain why the code is doing what it's doing. If I find comments answering 'what' or 'how', I take that as an indicator that the code is not written well enough.
- masklinn 13y agoSometimes you don't want to write the code "well enough" either, e.g. if you're reifying a standard algorithm I think it's a better idea to directly transcribe the original paper if possible, and stick as close to it as possible (including the usually dreadful naming conventions). And in that case I usually add the paper's pseudocode above the corresponding transcription as well to make the mapping even clearer.
- Shish2k 13y agoOn the contrary, an approximation of some code I've written: function do_search($query) { if($database->type == "mysql") { return __do_search_stupidly_because_mysql_is_shit($query); } else { return __do_search_sensibly($query); } }
- foobarbazqux 13y agoSo a comment could explain why MySQL is shit, what versions, whether it applies to MariaDB, whether there's an open defect, how your algorithm is different, etc. Presumably whoever wrote this code learned some of that metadata, so it's helpful to keep a record of it.
- IanCal 13y agoMost usefully, I'd like to know what the consequences of doing the obvious thing are. Maybe they don't matter any more (high memory usage, cpu use, etc) and we can trim the codebase, or it's still a NEVER CHANGE THIS OR WE LOSE OUR JOBS level issue. I'd much rather see a comment like /* * Inputs of integers near INT_MAX cause significant CPU load * in MYSQL versions 4.2 <= x < 5.8 (latest at time of writing) * Bug tracker http://mysqlbugtracker/issue/4 */ Than lolz_mysql_is_shit(foobar) As a relevant point, we've got a large comment in our codebase linking to issues and discussions of the problem of excel reading csv files containing £ symbols with particular encodings. If you didn't know the issue, having `format_excel_is_dumb(file)` wouldn't help. I am happy classifying comments as "you should have a reason to add it and keep it" rather than "bad code, always remove". Still, I suppose it's hard to generate buzz with an article that says "use your common sense" rather than repeating an old absolutist viewpoint.
- jonmb 13y ago"My code is so good it doesn't need comments!" says the first. "What the hell was this guy thinking?!" says the second.
- danso 13y agoI wholly agree that code comments can be greatly reduced by better code, most notably with code that has well-named variables and methods as well as through reduced complexity through refactoring. However, I think the way the OP title is phrased, "Don't Comment" makes too strong of a statement against comments, when I think the better, albeit softer statement would be: "Write Better Code and Fewer Comments" The main argument against commenting period is that comments are inherently not part of the workflow/compilation process, so it takes an extra level of cognitive awareness and maintenance to make sure they stay up to date with the specs. Other than that (very big) hitch, there's nothing inherently wrong with comments...except that in practice, a huge number of them indicate a code smell, as well as being a maintenance liability. This may have been outside of the OP's scope, but I think it's worth mentioning that well-written and copious tests can also serve the function of comments...unlike comments, they do break when the code they document is changed, and so thus they're easier to maintain in that you can't go forward without fixing them (which introduces its own maintenance chore, and so on and so on).
- chevas 13y agoYes, I was thinking the same thing. Your title suggestion is more accurate, but would probably draw less clicks. I prefer it when a title is bland, but the content is so astoundingly good. These are little surprises and they still find their way to the front page.
- nsmartt 13y agoI used to argue that well-written code needed no documentation, but I read various articles about documentation anyway. The takeaway was this: Even if my code is clear, neither I nor anyone else should have to read through a function in order to understand what it does. Reading a comment should be enough to use it.
- mhaymo 13y agoThis has the additional advantage of separating the specification from the implementation. If e.g. a javadoc comment says "@throws IllegalStateException when foo", then I know if I change the method, I have to preserve that behaviour.
- Uchikoma 13y agoI'm a proponent of self documenting code (method names, variable names, immutable variables etc) but this only helps document the WHAT and sometimes HOW but seldom the most useful WHY or WHY NOT or what I have tried before this and what didn't work so I changed it.
- quchen 13y agoI find it good practice to comment code for that other guy that is me-in-two-months. I just rediscovered some semi-old code and boy am I happy about the comments.
- dragonwriter 13y agoYeah, good comments help support DRY. Not so much DRY in the code, but avoiding repeating the mental work that led to the code (whether yours or somebody else's.) If the code is non-trivial, there is probably research, discussion, or analysis that went into producing it that the next person working with the code (whether you-in-N-months or someone else) either won't have done or won't have as fresh in their mind when they look at the code. Summarizing or providing references for that work stops it from being redone (or, worse for the code, the lessons forgotten and the mistake that it avoided reimplemented.)
- gregjor 13y ago"Don't comment bad code -- rewrite it." -- The Elements Of Programming Style by Brian Kernighan and P.J. Plauger. 1974. Until your code is as good as Kernighan's you probably want to comment what you intended to do.
- _ZeD_ 13y agoKernighan does not say "don't comment good code"
- gregjor 13y agoYou can read what Kernighan wrote here: http://books.cat-v.org/computer-science/elements-of-programming-style/elements_of_programming_style.pdf http://books.cat-v.org/computer-science/elements-of-programm... Also see Software Tools and The Practice Of Programming.
- WayneDB 13y agoHe really doesn't say "don't comment good code". Reading page 141, he generally recommends that everyone should comment their code for non-trivial programs. Also, "One thing we will _not_ do is make pronouncements about how many comments a program should have."
- hyperbling 13y agoKISS!! comments describe why. code describes what.
- spoiledtechie 13y agoI thought this was just another stupid HN comment. Had to read it several times for it to make sense. Its solid advice.
- ErrantX 13y agoSpeaking from experience of a) working in a team and b) maintaining legacy code: Your code, no matter how good, will not instantly make sense to someone else. Comments are essential. Writing good comments is as skilled a task as writing the code. (as an aside; the most important comment is WHO. Because knowing who wrote/modified a block of code is ridiculously useful for all sorts of obvious reasons)
- _ZeD_ 13y agosvn / hg / git ... blame ? :D
- Roboprog 13y agoEven CVS has an annotate / blame / praise command as well, as do, for example, commercial systems like Clearcase and MKS source integrity.
- spellboots 13y agoIf you have to write who wrote a piece of code in a comment, you must not be using a decent version control system with a blame command. Which is a problem you should probably fix way before talking about comment styles.
- ErrantX 13y agoUh, that takes much longer. Blame is useful in more elaborate context but... comments are instant :) And that is important.
- jack9 13y ago> Blame is useful in more elaborate context but... comments are instant Blame is instant too, if you have a good and modern IDE. Can't always be relied upon, but once such a beast exists, just assume it's being used. Writing erlang? Sorry, inline comments. Writing JS/PHP? Leave it in git.
- vonmoltke 13y ago
- noir_lord 13y agoI use comments where nescessary but what I really wish the IDE's/editors had was the ability to hide all comments (not just fold but completely hide), I don't need to see the comment now as I'm writing the code and the model is in my head but I will want to see them in 3 months.
- scorcher 13y agoIts true one should FAVOUR self documenting code. Going to the absolute and never commenting your code is obviously stupid, there will always be cases when more context and information on "Why" is needed.
- _ZeD_ 13y ago"don't comment your code", as dogma, without thinking, it's just stupid. What sometimes happens, when you work on the same code base for month and you know it inside out, it's that you get some knowledge for granted. So you shift your mental needs (and the need to comment it out) from the "how the hell do I do this" from "why the hell do I need to do this" (there can be some crazy business rules, or some infrastructure limitations or whatever). The problem is, the knowledge of the code base is not easily transmissible from people to people. So it's still useful to leave some comment, specially on some "non intuitive" steps.
- jdbernard 13y agoThe problem is, the knowledge of the code base is not easily transmissible from people to people. So it's still useful to leave some comment, specially on some "non intuitive" steps. Having just come from a team where code was well-written but poorly documented, this is important. It is the difference between it taking me 20 minutes and 4 hours to implement and test a small change. If the code is well-documented I can quickly find my way around and locate the behaviour I need to change. Again, if it is well documented it is easy to see how this relates to the rest of the system and I can make good decisions when I make my changes. If the whole process is well-documented I have a good starting point for what acceptance tests I should run to make sure it works as intended, and what kind of regression tests I should put in place or modify. Without documentation I must read and decipher a much larger body of code, much of which ends up being unrelated to what I am working on now. Even in the best code-bases there will be code that is not clear without a pre-existing knowledge of the code-base as a whole. I am likely to make time-consuming mistakes because I do not understand some edge-conditions or complex interaction.
- jwilliams 13y ago"My code is so good it doesn't need comments" is usually untrue. Don't fall for it. If you can name an API or framework that you use that has near-zero comments... And benefits from that, I'd like to know. I can name plenty that are a pleasure to use because of clear, replete documentation. If you're thinking your code is different from an API, you're right - it's worse. An API is designed for consumption, whereas your code is buried. It might not get look at by another human for months... or years. Who will be looking at that piece of code next? You? Ok. Be your own worst enemy. More than likely it's someone else looking. And why? Maybe because it doesn't work like it should, or conditions have changed, or it needs to be extended. Bad documentation can be just as bad as bad code, but "don't comment your code" is a road to madness.
- foobarbazqux 13y ago"My comments are so good they don't need code" is usually untrue too...
- talmand 13y agoNo, it's untrue all the time because it doesn't make any sense.
- foobarbazqux 13y agoSurely it depends on what your program is trying to not do.
- ErrantX 13y agoMy favourite piece of code that used to be in our code base was a set of empty PHP files with the comment "this file intentionally left blank". Created so that the core framework could be unit tested. (This was before I came on board and introduced the idea of filesystem mocking).
- NoodleIncident 13y ago
- amouat 13y agoPersonally, I like Linus's take on comments: "Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it's much better to write the code so that the _working_ is obvious, and it's a waste of time to explain badly written code. Generally, you want your comments to tell WHAT your code does, not HOW. Also, try to avoid putting comments inside a function body: if the function is so complex that you need to separately comment parts of it, you should probably go back to chapter 6 for a while. You can make small comments to note or warn about something particularly clever (or ugly), but try to avoid excess. Instead, put the comments at the head of the function, telling people what it does, and possibly WHY it does it." https://www.kernel.org/doc/Documentation/CodingStyle https://www.kernel.org/doc/Documentation/CodingStyle (Chapter 8)
- amouat 13y agoHmm, maybe I'm just assuming Linus Torvalds wrote that - it could be another kernel dev.
- kstenerud 13y agoI read the second block of code before the first. Just reading the second blob, I had no idea what the code was actually doing. Part of this is because I only have a peephole view into what's going on. I don't know what CalculateResultPairForNextStage() does, for example. My only clue that DMA is even involved in this code is the comment about resetting the source. Perhaps you have a big beautiful block comment in the header that explains what this component does, but just looking at this example things are far from clear. I'm also wary of the refactoring. The _csHoldoff check and decrement happens every loop in the first block, but only once at the end in the second block. Of course I have no idea what _csHoldoff is or does, nor do I know why there's a "cs" prefix on it. Hungarian notation? Some variables have it, and others, like _centerFrequency, don't.
- metaphorm 13y agolinkbait title. not a very good article. I think most of us here know about the dangers of stale comments, or spammy comments. I also think most of us know that writing good, descriptive, and up-to-date comments is basically essential.
- beat 13y ago"Clarity" is not a substitute for comments. The only thing I've seen that really substitutes for comments is a rich, easy to understand unit test suite. But even that is problematic, as it usually covers a lot of edge and corner case situations that aren't relevant to the end user.
- ttflee 13y agoI was trying to write good code instead of document a lot. But now I feel that a few comments is necessary, given that you write the stuff that matters. Maybe we should all try to comment as concise as possible, and write it just like SEO.
- deleted 13y ago[deleted]
- kbenson 13y agoThe problem with this is that he assumes the context will always be known to the reader. I find that many assumptions about what is obvious in code have to do with the context the code is in. That context may be closely surrounding the code block, or with may extend to many lines before and after. If you have not been working on that entire section for a time, the context is not present (or only partially present), and as such all your thoughts on what is obvious may be subtly wrong. This is analogous to program state. The farther you explore in either direction of the target code, the more of the possible state you can infer. Comments help is make these inferences without having to explore as much. Without comments we are forced to explore more of the program to build a better mental model of the possible states. Comments help us by providing hints as to the context (state).
- talmand 13y agoAh yes, there's nothing like wanting to use the new hot API and realizing you have to read almost all of the source code to understand how to use it because the code is so good it didn't require comments. Because I see good comments as a form of documentation. Can comments be abused and detrimental? Sure, but then so can code. Especially in Javascript where parameters of a method are not typed, so if you want to know whether you should be passing a string or a number you have to read through the code to find out. Or, you know, a single line comment saying what to pass might be helpful. The problem is not the comments. The problem are the coders that follow behind to update a block of code but can't be bothered to update the comments to reflect the changes. If your code is so good it doesn't need comments then it seems it wouldn't require git commit messages either.
- Roboprog 13y agoPlease don't summarize what your functions / methods do, make me read them in their entirety to find out. Er, what? "Illiterate Programming" paradigm?
- yannis 13y agoI have been coding for over thirty years and the best reason for commenting your code is that the older you, will not remember what the younger you was thinking when he wrote the code.
- russelluresti 13y agoWorst. Advice. Ever. Please comment your code. First, you're probably not going to immediately remember what the code does 6 - 12 months after you write it and when you have to come back to it for an update it's going to take you too long to figure out if you actually read the code. Comments make familiarizing yourself with your old code much faster. Second, any other teammate who touches the code is going to hate you if they have to read your code to figure out what it does. There is nothing worse than looking over code written by someone else when there are no comments.
- dkuntz2 13y agoI disagree. And I'm not sure you caught the tiny part at the beginning when the author talked about how why comments are good, but what and how comments are mostly useless. Yes, there was only a tiny mention in the post, but it was there. I think that what and how comments are useless because they're literally the code itself. Comments like 'increment by two' are useless, because the next line literally says `x += 2`. If that comment was expanded to be something like 'increment by two because ...', explaining why x is being incremented by two, it becomes useful, and I think the author agrees. I think the reason these posts get as much traction as they do every time they're posted is because people tend to write bad comments. In my experience as a CS tutor at my college, most new programmers either write useless what/how comments or no comments at all. The problem I see with these posts are that they don't talk about how there are good kinds of comments, but that everyone should just make their code cleaner and everything will be great. If more time was spent talking about how to write better, more informative, and relevant comments I'd like these posts more.
- MetaCosm 13y agoComment rot is like wiki rot -- all too common, and often more confusing. There are a couple good rules of thumb I follow. 1) If you are writing a comment, make sure it is a "why" and not a "what" (why this code exists, not a description of what it is doing). Why comments often survive refactoring, you might entirely redo the login system, but the reason you do it is still so people can log in. 2) If you find yourself documenting the "what" about code -- take a moment, and think really hard about why it is confusing. If it is accidental complexity (your fault), refactor it. If it is fundamental complexity (problem domain is a bitch), don't add the documentation to the function, put that knowledge in the tests. Nothing is as harmful that a bunch of gotchas buried in comments no one will read, and will eventually rot and not even make sense after the code is refactored.
- dirkdk 13y ago+1 I like to refactor just names of variables and methods, instead of writing comment what it actually does.