TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Comment your damn code

34 pointsby yShrikeover 12 years ago

25 comments

larsmakover 12 years ago
I'm against commenting code, with two exceptions:<p>- You're implementing something complex (like an algorithm)<p>- You're implementing something stupid (typically a workaround for something that could not be done in a more elegant way, and you want to explain why it can't be refactored)<p>If the code is well written it is also self explanatory. This can be done by structuring / formatting the code well, into methods, classes, packages - and naming these constructs in a reasonable way. Naming variables is obviously also very important - and be consistent!<p>In my opinion comments only clutters the code, and in most cases reduces readability. Like mentioned before you cannot always trust that the comments are up-to-date, but the code certainly will - so I believe time should be spent making the code readable instead. "Look, there is what you intend and what you write" - those should be the same, there should be no in-between.<p>My primary language is Java by the way (about 10 years of experience).
评论 #4772903 未加载
评论 #4772949 未加载
评论 #4773046 未加载
评论 #4772980 未加载
bitdiffusionover 12 years ago
"Look, there is what you intend and what you write. Your bugs are in between the two."<p>Umm no. Bugs are usually<p>a) a misinterpreation of the requirements (no amount of comments are going to save you) or<p>b) a (hopefully) subtle error in the code - again - I don't see how a comment is going to help you unless the comment is practically pseudo-code which I (hope) nobody is advocating.<p>Anyone have an example of the typical type of bug that is easier to fix when there are comments around? I agree about commenting "non-obvious" code though - at least in terms of it's intentions. Not necessarily as a way to fix bugs, but to prevent the next programmer from removing something that looks superfluous because nobody can remember why it's there. Something like (totally made up):<p>"Assign the customer id as a prefix to the comment field; SAP expects the format of &#60;customer_id&#62;__&#60;comment&#62; during import".
xradionutover 12 years ago
I've been writing code in some language or another for almost three decades. My headers, comments and READ_MEs usually end up helping me more than anyone else.<p>When you have multiple projects in muliple languages for tens or hundreds of clients over the years, the last thing you want to do is open a project or repository and see little or no documentation. And you don't want to have to figure out what/why the heck you did in 2007 and explain the project to coworkers.<p>I guarantee you that clients and coworkers will pick the worst optimal time to want revisions. And if I spend the time upfront to make it simple for a junior member of my team to take ownership of a project in the future, my life becomes better.
h2sover 12 years ago
Note that the following does not count as commenting your damn code:<p><pre><code> // Get the account holder currency $currency = $accountHolder-&#62;getCurrency(); </code></pre> Imagine several 10s of KLOCs where 99% of the comments are as worthless as this and most people are content with their efforts because they believe they are commenting thoroughly.
评论 #4772927 未加载
评论 #4772913 未加载
评论 #4773049 未加载
rvkennedyover 12 years ago
Why comments are important: they represent <i>intention</i>.<p>A reasonable complex method can have a wide variety of inputs which the author can't be expected to have tested across the entire range of values. For example, if you have six boolean inputs, you have 2^6=64 possible combinations.<p>If you have six <i>integer</i> inputs, you have roughly (4e9)^6=4e57 combinations, which is more than the number of atoms in the Earth.<p>Expressing your intention means that when you (or someone else) come back to the code to change it, you can at least have an awareness of whether the behaviour you are seeing is in line with what you intended. Because a bug might not even be a bug - in that code - but a misuse of a method for something it wasn't meant to do.
评论 #4772948 未加载
lmmover 12 years ago
Nope. You need to comment every nonobvious decision, but if you write code the right way then the nonobvious decisions disappear. A well-written method doesn't need explanation, because it obviously couldn't have been written any other way.
评论 #4772797 未加载
评论 #4772808 未加载
评论 #4772790 未加载
评论 #4773027 未加载
klibertpover 12 years ago
So many comments already... Well, that's to be expected.<p>I agree with OP wholeheartedly, but I think he misses one obvious thing and that is the fact that commenting code is hard. Very, very hard, laborious and easy to get wrong. It hard even for people who are used to writing prose, like heavy bloggers for example. It's made even harder if you don't write in your native language, and "even harder" here means "almost impossible for many".<p>Unlike many programmers I enjoy writing, which should be visible to anyone who sees my comments here. I have quite a lot of background in writing various texts, from short stories to essays. Yet I find commenting - or rather - writing good comments in code very difficult. I think I can do this, I got praised for the comments at one time or another, mainly for their clarity (instead of sheer volume) which makes me extremely proud, but the fact is that I spend almost as much time on commenting the code as on writing it... Sometimes I write comments up front along with tests, to clarify my thoughts, sometimes I write them after coding something, but that does not change the difficulty at all.<p>I think the art of commenting code - and it is an art, no doubt about it - is comparable with debugging. As we all know, debugging something is twice as hard as coding it, so - by definition - if you code something to be as clever as you can you won't be able to debug it. Nor comment it properly.<p>And many of comments such as "I'm against commenting code" stems from this, I think - in many cases we're forced (in school, mostly) to code near the limit of our ability and then we're forced to comment; of course those comments are crap, but that's what we see for a very long time. Then we get used to it, we kind of expect comments to suck, and we think that they are a waste of time.<p>Not so. They are just very, very hard to master and there are very few people who would even try to teach about them. We can say whatever we want, but it won't change anything. We need to find those who really <i>can</i> write good comments and make them teach others...<p>After all this I have to admit that I doubt it's possible. Don Knuth tried with his "literate programming" idea and failed miserably. Among 25 programmers at my current work just one even knew the term, but didn't know any specifics, while all of them know who Knuth was. I don't mean to say it's hopeless... But it certainly seems like that to me.
jimflover 12 years ago
Every line of code is a liability.<p>Every comment is also a liability, especially in light of the fact that the comment may, over time, drift away from the code. I sometimes wish I had an IDE that would color nearby comments red (and prevent commits) when code changes.<p>Which is to say, make comments where necessary, but own the liability, and strive to remove comments you find by making the code more obvious, just as you would strive to remove code to make it simpler.<p>If you want to record your intent, write a test.<p>Edit: accidentally a word.
rrreeseover 12 years ago
I think Jeff Atwood sums things up nicely: <a href="http://www.codinghorror.com/blog/2008/07/coding-without-comments.html" rel="nofollow">http://www.codinghorror.com/blog/2008/07/coding-without-comm...</a>
评论 #4772896 未加载
agentultraover 12 years ago
I used to work with someone who would start writing a function or module by writing their code as comments.<p><pre><code> # First we iterate over the directory and get a list of files to process ... # Then we process them </code></pre> This "pseudo-code" would then be filled in by the actual source code ei intended to write. And once ei was done the comments would stay in and be checked in for code review.<p>Nothing was more tedious to read. It's like having a narrator tell you exactly what each character is going to say right before they say it. It is quite maddening to this reader and I had to constantly review this sort of code.<p>I had to politely approach the person writing this code and explain this to them. Comments are not for describing what can already be read. One's code should be written in such a way as to inform a programmer maintaining the code to its purpose and utility. That means short, single-purpose functions, conventions, idioms, and all of that. But it also means that comments should only be used when you're going against convention or doing something hack-ish on purpose.<p>I saw fewer lines of comments until a fresh, new young team member joined...
评论 #4773264 未加载
评论 #4773120 未加载
myoffeover 12 years ago
I prefer tests over comments.<p>Comments can't guarantee to represent what the codes does always. "Don't be lazy" is a fine argument, but it takes one time that you are under pressure to ship right away and you don't comment. Tests, on the other hand will keep failing until they describe the updated version of the code.<p>We should strive to make code obvious, when it's not obvious, then you should comment, or better: simplify your code.
augustlover 12 years ago
There's usually a large amount of comments and metadata relating to code that isn't present in the source files themselves, but in an external database:<p><pre><code> git blame path/to/file.txt </code></pre> I think this is one of the most underused tools in software development! I wish more editors had features like "show me the history of this class/function" etc.
评论 #4772992 未加载
评论 #4773281 未加载
joefreemanover 12 years ago
I also disagree. Commenting is something I do when I'm being lazy - too lazy to make the intent of the code obvious. Sadly, this is also the impression I get when I see comments written by other developers. (That said, method-level documentation is still something I'm on the fence about.)
darrencauthonover 12 years ago
"Every 3 to 7 lines of code you'll find some amount of editorializing. Maybe every few hundred lines you'll find a good joke too."<p>I think there's the issue. In applications I write, every 3-7 lines of code is refactored into a method that is named exactly what it does, and every few hundred lines of code (usually much less) is in a separate file and class named on what he does. Broken out like that, there's not many places to put a comment that would be of any use.<p>But not broken out like that, of course you're going to need comments. But I think you'll find that comments aren't even enough.<p>"I know what the code says. But tell me the intent."<p>I think unit tests and expressive code work much better to achieve this goal.
评论 #4772984 未加载
ChrisArchitectover 12 years ago
"thousands of lines and zero comments merry christmas and a happy bus accident"<p><a href="http://theprofoundprogrammer.com/post/27214842818/text-thousands-of-lines-and-zero-comments-merry" rel="nofollow">http://theprofoundprogrammer.com/post/27214842818/text-thous...</a>
xutopiaover 12 years ago
Test it first and you'll notice that comments become near useless.
andrewcookeover 12 years ago
ok, so i wrote some code yesterday. i didn't write it expecting anyone to read it (i mean, not critically on hn), and it's not as good as i would like, but it has no comments (apart from at the top of the file explaining how to use the program).<p>so, people who are saying "just comment it" - what would make a big difference to this code?<p><a href="https://github.com/andrewcooke/amcl/blob/master/amcl.py" rel="nofollow">https://github.com/andrewcooke/amcl/blob/master/amcl.py</a>
评论 #4773067 未加载
评论 #4773101 未加载
评论 #4773065 未加载
评论 #4773066 未加载
blackyskyover 12 years ago
You should comment your code if and only if your algorithms has special pre-conditions and post-conditions otherwise your choice of variables name should make your code speak by itself... exemple of pre condition: your algorithm don't handle non latin word ... exemple of post condition , your algorithm only return a specific format like aa-bb-cc ...<p>or like my teacher said use your common sense, make your code as clear as possible.. I should understand it without you ...
givanover 12 years ago
Write your damn code so that is easy to read and understand so it doesn't require comments.<p>Code comments are like subtitle for movies, when the code is chinese and you don't know chinese they are helpful.
gte910hover 12 years ago
If you do the normal, please do not comment your code. If you did the strange, please explain it briefly, but maintainably.<p>If something is broken, link to something outside the code (aka, vendor bug).
CKKimover 12 years ago
If the author had simply chosen a few examples of good commenting in code and exhibited them, then he wouldn't have had to write this article explaining his point..or would he?
ruggeriover 12 years ago
&#62; I've been doing this a long time. Chances are, way longer than you.<p>Stopped reading when I realized the author wasn't going to be reasonable.
natasham25over 12 years ago
This is why I'm a big fan of TDD. You're basically commenting your code in your tests without having to comment the actual code.
评论 #4773465 未加载
jasonlotitoover 12 years ago
This comment leaped out at me:<p>&#62; what is going on in this icky mess<p>This is a sign that your code is poor, and comments aren't going to help poor code. When you need to comment to overcome poor code, that's a sign your code needs help, not your comments. Thinking comments are going to solve this is a losing game. If this is the way you think, then you'll continue focusing on propping up poor code with comments.<p>Comments are inherently dangerous. Not because commenting is bad, but because comments are inaccurate. When you write a comment about a block of code, the comment will never be as precise as the code. You'll write about the intent of the code, but even the intent is unclear. The reason for this is with the language we use to write comments. These comments rely on context of the person writing them. And writing is not easy. Describing a block of code that will determine the longitude and latitude is difficult. Do you describe how it does this, the reason it's doing this? Do you talk about how it accomplishes this? Why you are doing it this way? What's important.<p>For example, take this bit of advice about "good comments":<p>&#62; A comment should describe the why or the goal, not the how.<p>So, a good comment would be as follows:<p><pre><code> // We accept a search string from the user and transform it // into a latitude and longitude from the location service. // We do this because the user knows about where they are, but // we don't have access to their GPS data at the time, so this // is a great way to get local data at some level </code></pre> So, this explains "Why" we are doing this, "what" we are doing, and the goal. However, nothing here is special to a comment over well written code,<p><pre><code> public Location getLatLongFromUserLocationSearch( String search ); </code></pre> That does far more, and is more accurate, then the original block of text. More importantly, that original block of text is fundamentally flawed: it's blatantly inaccurate. It also encourages laziness. After all, if your poorly written code is resolved by simply adding a comment, instead of tackling the more challenging part of writing quality code, you take the simple way out of adding in a, most likely, poorly written comment.<p>&#62; Look, there is what you intend and what you write.<p>This remark is amusing. Between the two, the chance of a comment being wrong is greater than that of the code. The code is at least tested at some level. The comment is not.<p>&#62; Don't be lazy<p>This is an article focusing on writing comments well to cover up for confusing code? The assumption here is that it's easier to write comments well. I'm sorry, but if you can't write the code cleanly in the first place, how are you going to effectively write a comment that will clear things up.<p>&#62; You're a Journeyman<p>Damn right, and I know that there are far better avenues than writing comments in code to accomplish that. On top of this, the example is absurd, as he's suggesting not limiting what your comment includes to what and how, but also why: "Tell them why you choose to use a Tuple in this case."<p>&#62; So you type 40 - 60 wpm. So then tell me again why aren't you writing comments while you blaze through your code?<p>Oh, the travesty. To equate typing speed with quality. And make no mistake, that's what is being done here. Somehow, typing speed is the issue. It's akin to relating line count to performance. Listen, typing speed isn't the issue. It's quality, and quality takes time. Writing quality code is not defined by your typing speed. Neither is writing quality comments. It doesn't take a long time to write quality comments because you lack typing speed, but because writing clear comments is hard work.<p>&#62; You're going to get old<p>If you weren't clear that an ego the size of Jupiter was writing this post, this section will slam the point home.<p>First, let's get this out of the way:<p>"I've been doing this for a while, probably before you entered middle school."<p>Your age does not qualify you. Bringing it up again and again only means it's the best qualification you've got. Wisdom isn't about age, though age gives you more opportunities for obtaining wisdom.<p>As for getting older, there are far better mechanisms for ensuring that you know what the intent of the code is, from both a business sense, and from a code sense.<p>Honestly, the biggest warning to relying on comments to resolve deficiencies in other areas is this article itself. It's poorly written, confusing, and even contradicts itself.<p>In the end, it's some of the same tired advice presented in a brash way. This brash method, employing vulgarity and rudeness, fails. "Comment your damn code because I said so and I'm old and that makes me right" is essentially what it amounts to.<p>I'm harsh, James, because your article is harsh. It preaches writing comments, and does so in poorly written English.<p>In the end, commenting your code is the worst thing you can do.<p>Commenting your code well, however, is not. But commenting your code well is a challenge. It's not easy, and should not be seen as trivial.<p>Well written code takes longer than 30 seconds to write. Well written comments take longer as well. And well written comments in well written code are not added every 3 to 7 lines.
评论 #4773235 未加载
Toshioover 12 years ago
Well, I disagree.<p>Test-drive your damn code. The difference in positive impact will be a few orders of magnitude.
评论 #4772958 未加载
评论 #4772982 未加载
评论 #4773154 未加载