Don't Comment Your Code - Write Better Code
sam-koblenski.blogspot.com
sam-koblenski.blogspot.com
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.
(This was before I came on board and introduced the idea of filesystem mocking).
I still don't see this as a convincing argument.
Our greatest constraint is time. So the question becomes do I spend my time writing comments or do I re-factor the code I wrote to make it more readable?
I always opt for re-factoring my code.
Have you read some of the comments most developers leave? They either explain the most obvious inane functionality or use it as their personal todo list. And sometimes they do both. That is not helpful.
In instances where I know my code will be a critical component which will be utilized by many others, I opt to write documentation rather than comments. And there is, of course, a difference.
Comments are inline, documentation is frequently split out. Comments are frequently inane explaining the obvious, while documentation goes in-depth into not only how the code works, but what it is trying to accomplish and why. Documentation also provides examples of use, which is far more useful than anything else. When I reach for the documentation option, I almost always include a separate markdown file with the same name as the original file. There are then a ton of options in terms of software that aggregate those files into a searchable, indexed collection.
Focus on code quality and if some sort of annotation is necessary, write documentation, but don't leave comments.
Can you show us any concrete examples of high quality, comment-less codebases? The last (mostly) comment-less source that I read through last year was Node.js and I wouldn't exactly call that high quality or well documented.
No.
Quite simply, there is a collective perception that if a codebase lacks inline comments, it's of poor quality. Very few would dare to publish such a work.
I have a different challenge for you.
Take a high quality codebase and delete all the inline comments. You'll find it's just as readable, if not more so. How much better would it have been if the coder had spent the time writing better code rather than adding superfluous comments?
None of these contribute directly to achieving a theoretical maximum output of SLoC. If that's you're metric, I don't think it's a good one.
Aside from niche projects - A great deal of time goes into realising software. The incremental cost of comments is minuscule.
I have lots of challenges and bottlenecks. The time to type comments isn't one of them.
That's certainly not my metric and I definitely don't believe it's a good one.
My metric is readability. The ability to return to a piece of code 6 months down the road and be able to understand precisely what's happening.
> I have lots of challenges and bottlenecks. The time to type comments isn't one of them.
Oh, I know. It's very easy to add a comment that you think will help clarify things down the road, but instead, ends up being more cryptic than your code.
By definition, a comment is something short and half-thought out. It's a comment.
As I said in the post up above, stay away from comments. If you have to annotate, write documentation instead.
Who is the authority on whether commentless code is good or not? Could this possibly be completely subjective? Hmmm.
> Oh, I know. It's very easy to add a comment...but [it] ends up being more cryptic than your code.
You don't know that :)
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.
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.
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?
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.
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."
I suppose in the end it's just a matter of opinion, isn't it?
If a team is so poor that they don't properly document what they do I suspect that the comments is the last thing to worry about :)
Same with shit code and non-self-documenting code no?
But I still think some comments are better than absolutely no comments...
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.
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)
Blame is useful in more elaborate context but... comments are instant :) And that is important.
1) Changing version control systems may be an unwinnable corporate political battle, while changing comment style may just be a team decision.
2) Not everyone who may need to understand or modify your code may have access to your repositories. I worked on a program where partner companies were provided source snapshots for developing their own algorithms but were not allowed access to our repositories.
IME, the only use it usually has on its own is knowing which people that are no longer on the team to blame to blame for the poor state of the code (both the operational parts, and the absence of useful code comments on the intent or rationale for the current code structure.)
WHO is not the most important comment (though its probably the most universally necessary part of a comment -- a need for a who comment always implies the need for some other comment, and most other comments should include a who.)
The only reason I've ever had for knowing who wrote code is if the code+comments+tests do not adequately explain what's going on and I need to know. On most of those occasions the person who wrote the original code had already left the organisation.
"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 (Chapter 8)
"What the hell was this guy thinking?!" says the second.
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.
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.
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.
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.
> 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.
And in that case I usually add the paper's pseudocode above the corresponding transcription as well to make the mapping even clearer.
function do_search($query) {
if($database->type == "mysql") {
return __do_search_stupidly_because_mysql_is_shit($query);
}
else {
return __do_search_sensibly($query);
}
}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.
http://sourcemaking.com/refactoring/replace-conditional-with...
In my mind code is for the "how" to do a thing, comments is for the "why".
While sometimes some bugs in some library / infrastructure element bites you badly, I still think calling a function "do_workaround_XXX_because_YYY_is_shit" it's not a good practice. And, hey, in comments you can articulate your hate for mysql with more space :D
I prefer to be parsimonious with comments, but strange hacks, workarounds for bugs, and other places where otherwise clean code meets the real world should probably have at least some description of why that particular workaround was chosen, and not some other more obvious option.
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.
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.
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.
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.
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.
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).
Until your code is as good as Kernighan's you probably want to comment what you intended to do.
Also see Software Tools and The Practice Of Programming.
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."
comments describe why. code describes what.
Er, what?
"Illiterate Programming" paradigm?
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).
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.