by recycleme · 14y ago · 0 comments
A reason given to me was that "it takes up too much time to comment and when you make a code change you need to make a change in the comments as well." To that I say, so what! I would like the future me (or the future programmer) to have full knowledge on what's going on in the code.
If they express those views, I wouldn't call them senior.
Commenting is necessary to express invariants, and to summarize complexity that would otherwise require each reader of the code to understand the code itself in depth.
Those are actually closely related things.
Very few languages are capable of succinctly expressing sufficiently detailed invariants. Some are better than others -- maybe they support Maybe monads instead instead of possibly-NULLs. However, it's rarely possible to express -- purely in code -- what the code is supposed to do, what the input is supposed to be, and what the output is supposed to be.
Failing to express those things means that any future reader/maintainer will be forced to trace your code, in its entirety, to reverse-engineer how it is probably supposed to work. In many cases said maintainer can never know for sure without tracing your code and ALL code that calls your code -- otherwise, any change to that code could break undocumented behavior that other code relies upon.
Anyone who advocates against comments is justifying laziness, and they're wrong. The only supportable argument for not commenting is if a language is sufficiently powerful and succinct enough to express all the invariants normally expressed through comments, as well as being readable enough to permit a future maintainer to understand the design of the code without requiring them to spend an undue amount of time studying its inner mechanics.
I'm not aware of such a programming language.
“Don’t comment bad code—rewrite it.”
—Brian W. Kernighan and P. J. Plaugher
Is that senior enough for you? > Anyone who advocates against comments is justifying
> laziness, and they're wrong
No, they are actually advocating to put more effort in thinking about stuff: how you name your functions/methods/whatever, how do you name your arguments/parameters, how do you write the code itself.To anyone interested I recommend to get a copy of "Clean Code" and read the relevant chapter. IIRC "Code Complete" mostly agrees.
No. Have you read 70s and 80s C code? Tried tracing through the original UNIX kernel sources? Tried working with them?
To understand all the invariants of one small aspect of the system quite often requires tracing through the whole system until you get to a well-documented input/output module point (via comments, man pages, or otherwise).
Also, the quote (aside from it being out of context) says to not comment bad code.
> No, they are actually advocating to put more effort in thinking about stuff: how you name your functions/methods/whatever, how do you name your arguments/parameters, how do you write the code itself.
You can't define all the invariants -- or summarize for readability -- in pure code.
Yes. It's some of the easiest to understand code I've read. For example, http://unixarchive.cn-k.de/PDP-11/Trees/V6/usr/sys/ken/slp.c
They're actually quite decently commented. The functions describe what they do clearly, and the bodies show how they do it tersely, with comments around the sticky bits.
Have you read through the original Unix kernel sources? Claiming that they're uncommented and difficult to work with is surprising. (On the other hand, the directory structure could be better.)
"When you have spoiled ingredients, dispose 'em. Do not try to cover the bad flavor with condiments." - Famous Master Chef.
"You see? Master Chef does not like condiments. They take away the natural flavor of the food and anyone who uses them is an idiot who never will be a true cook". - Zealot Wannabe.
That's advocating against bad code, and specifically the fairly widespread practice of commenting what it does rather than fixing it.
It's not a blanket statement against comments in general.
There are so many problems with trying to make up for unclear code in comments, that's a real losing battle. I recognize that it may be worth breaking that rule sometimes, but then it is worth noting that, and flagging it so that other programmers can see and fix it. A comment like "#FIXME: This code is unclear: What it does is...." is perfectly acceptable.
Comments are for collaboration. You do NOT want to make them even appear useful for debugging.
Is that a problem? Even in code that has good comments, I always skip the comments and go straight for the code. Comments are okay if the code needed to employ hacks for some good reason, but otherwise I've never met a function that I wish had them.
I often wonder if people come from different backgrounds, which leads to completely different points of view on the matter. Personally, I find code easier to read than natural languages, but that doesn't mean everyone is the same and I respect that you might find comments useful. But why then assume that everyone needs comments?
Come on, this is stretching credulity. Either that or you don't value your own time.
1) API documentation says this: does the code conform? If not, either the specification is bad or the code is bad.
2) Comments inform collaboration, but do not inform debugging other than as API documentation.
As a result, I feel that is a different matter to commenting for the purposes of code maintainability, which is what the parent poster is speaking to.
Yes, because it means I might need to read 6 layers of code and wind through multiple modules, instead of just reading the top layer that defines the invariants of input/output for a module.
I wouldn't be so hasty as to assume that anyone making the above claim should be taken literally. Indeed, frowning on detailed commenting (or commenting at all) seems more like hyperbole then anything. After all, what is "detailed commenting"? It's not indication of quality.
// Increments x by 1
x++;
That is a detailed comment, but hardly worth while.And the commenting at all remark does not indicate that all commenting is to be avoided. Rather that comments should be scrutinized. After all, comments are indicative of a confusion. If your code requires a comment to explain itself, maybe it's best to review what you are doing, and work to avoid confusion.
> it's rarely possible to express -- purely in code -- what the code is supposed to do, what the input is supposed to be, and what the output is supposed to be.
It's actually fairly easy to do that in all languages I'm aware of. It's part of the reason you have Unit Tests. To document what the code can do, but also the expected input and output. More often than not, we forget that.
I dislike the idea of promoting comments for the sake of comments. I much prefer the push for clarity in code. Limiting clarity to comments is bad form, and generally those pushing for lots of comments excuse confusing code because they use comments freely. They also believe that these comments will remain relevant, and make the call that should they not, it's not their problem, but the programmer that fails to update the comment.
This is akin to blocking user out of an account after the first wrong password entered. It's their mistake, after all. And our jobs as programmers are not write robust code. Comments cannot (and should not) affect that code, and relying on comments to provide the quality missing from the code is lazy.
I'd be more in line to say that if your Unit Tests aren't concise, then it's a problem with your Unit Tests, or at least, your implementation.
> and they're not a suitable form of documentation
Well, the output that you can generate form unit tests can easily be documentation, explaining in great detail exactly what can be done with what is being tested, without any hand waving either.
Still, that doesn't take away from everything else I said. In the end, if you rely on comments to explain your code, your code is probably lacking.
That is a gross generalization. I do not, in general, comment my code (and I know and work with many other programmers who do not) but I go to great lengths to ensure that my code is easily understandable. Commenting is not the only way to communicate intent.
I suspect we work in different sections of the industry, but in my world, comments are often a red flag rather than a welcoming sight!
You're almost certainly not succeeding, because unless you work with a language far more expressive than one I've seen previously, then your code can not express all the information I need to work on your code.
A complete lack of comments is on my top three list of "bad times ahead" warning signs when I inherit a codebase.
The other "bad times" warning flags are:
* A lack of documentation
* A lack of automated tests (integration, unit, or otherwise).
These three things can make or break maintainability on their own, and they also often serve as a proxy indicator for just how much thought an engineer put into fully understanding the invariants and edge-cases of the code they've written.
The hard part of writing comments, documentation, and tests is in understanding invariants and edge-cases. The easy part is writing down what you've understood.
> I suspect we work in different sections of the industry, but in my world, comments are often a red flag rather than a welcoming sight!
Unless your section of the industry has no interest whatsoever in maintainability, I'm not sure our respective sections are very different.
You seem pretty convinced, so I don't have high hopes of changing your mind with a post on an internet forum, but in my experience most comments can be replaced by clearer names, better abstractions and better tests. The ones that can't tend to be about the "why" rather than the "what".
>Unless your section of the industry has no interest whatsoever in maintainability[...]
My primary motivation is maintainability, and your claims to the contrary come across as pretty condescending.
1) Copyright notices and brief (1-2 line!) file-level descriptions at the top of each file and
2) Comments that the code needed to have in place in order to run properly... Delete the comments and things break. I am not kidding.
Oh, no documentation and no unit tests either. We started adding unit tests and found that things like number rounding failed.....
Years later we are still replacing the old code as fast as we can. The obvious things including braindead security issues, were just the absolute tip of the iceberg.
Nowadays I write my documentation first, then code, then at least some tests.
I agree that commenting is not the only way to communicate intent.
I don't know what you mean by commenting code though. I find in general that the people who treat commenting as a last resort, and look for every other method to clarify code first, tend to also have some of the highest comment to code ratios, as well as the best comments.
This was driven home to me recently when I wrote some PHP classes for interfacing with LedgerSMB. I checked them into github and added the project to Ohloh, and was stunned when it said I had as many comments as code. But virtually all of these were interface documentation.
However, everyone makes mistakes, as you have pointed out, and once a comment is forgotten during refactoring, that comment has become a liability to the future maintenance or use of the code it describes. Given that comments are, by definition, not executable lines of code, commenting errors do not show up in code execution. Since most bugs only become apparent because of incorrect execution, commenting bugs are difficult to spot. This is a problem when developers read the comment instead of the code to discover the purpose and mechanics of the commented function or statement, and can lead to further errors in client code of the function or statement when the called code doesn't conform to the specifications expressed in the comment.
Now the developer who has to fix the code has two things to debug; the code as it is written and the code as it is described in the comment. Which has authority? How do you prove the correctness of a comment?
You can prove the correctness of code, because it can be executed. You can test it using the scientific method, trace its execution paths at runtime and by reading the calling code. You cannot do this with comments.
Additionally, every line of source code is a liability to the maintenance of the code. Each line out source adds computational and mental complexity to the program they describe.
For these reasons, good, verbose variable and function names to describe the what, and corresponding tests to describe the how and why are superior ways to describe code over verbose comments.
However
Code comments though are different. They are there to annotate code. They are incredibly useful in collaborative environments but only if they are used to organize, discuss, and debate the code, not describe it.
flatline3, I can tell you flat out that you are wrong. There are plenty of senior level programmers that are quite deserving of the name who deliberately comment very lightly if at all. There are also plenty of senior level programmers who think that verbose commenting should be required of everyone.
I have experienced both styles, both in forms that are implemented well and implemented poorly. I have read arguments for both sides. I have found that either can work well, and either can work out horribly. (Though attempting both at once is very much not recommended.)
Personally I prefer to work with (and write) code that avoids comments wherever I have any reasonable alternative (clear variable names, calls to descriptively named functions, error checks with error messages that make it clear what I was trying to do, etc). However when all other alternatives fail, I do not hesitate to comment.
The most important case where there is no reasonable alternative is in descriptions of an API. The code that is there is how it happens to work right now. If you want to know what you can rely on to remain true in the future, read the documentation. Anything not documented is not part of the API, and you should be prepared to find it changed in the next release.
Senior in name (and possibly years) only. I've spent enough years cleaning up messes to know that master programmers:
- Design carefully - Comment liberally - Test thoroughly
Thus they produce clean, well documented, understandable code. Skipping any part of that list is foisting delaying the cost for a much larger later reckoning of some poor future persons.
You might get away without commenting, but you're not doing anyone any favors. Skip all three and you're incurring significant technical debt.
I have no respect for programmers that think their sole job is to write code (no matter how "descriptive" it is).
> The most important case where there is no reasonable alternative is in descriptions of an API. The code that is there is how it happens to work right now. If you want to know what you can rely on to remain true in the future, read the documentation. Anything not documented is not part of the API, and you should be prepared to find it changed in the next release.
All functions are API. Some is mutable, because you can check and modify all callers. Some is immutable, because you can't.
It all needs to be documented, and the cost for not doing so can scale exponentially as a code base grows.
Read the source code for Arc. You'll find that Paul Graham is not a senior programmer by your definition. Read the source code to some of Damian Conway's modules. You'll find that Damian Conway is not a senior programmer by your definition (though his stuff does usually come with wonderful documentation). There are plenty of other examples of talented programmers in your books are not senior.
From where I sit, I know nothing about you other than your account is about 2 months old and this discussion. In particular I know nothing of what you've done. However people that I respect a heck of a lot more than you have defended very light commenting styles. I've seen it work. I've also seen it fail. Ditto for heavy commenting styles.
Therefore, based on my own experience, I'm going to say that it is complex, with valid arguments on both sides. Which puts me on about the same page as Steve McConnell's book Code Complete.
But I'm going to go further. The downsides of a comment heavy style have to do with the possibilities of the comments being misleading. People have to be very, very careful to maintain comments along with the code. Based on what I've seen, I would personally not trust any team of programmers to do this reliably without having careful code review processes. If you have this careful code review process to alleviate the potential issues with commenting, I would advocate a much heavier commenting style.
But there is one line that is very important that explains a lot of the difference:
It all needs to be documented, and the cost for not doing so can scale exponentially as a code base grows.
There are a lot of problems that scale non-linearly as a code base grows. There are two possible responses to this. The first is to try to create procedures to alleviate the problems that are intrinsic to growing code bases. The other is to maximize what can be done without growing your code base.
There is a fascinating data point on this that is cited in Software Estimation: Demystifying The Black Art. For projects of a fixed size (about 50k lines of code) there is a graph based on real world estimates of months to completion versus team size. Initially as teams grow, calendar months fall. Then the graph bottoms out with teams of 6-8 people. Then it starts to rise. And then falls again. It isn't until you get to teams of about 20 people that calendar months fall to the same level. (Given that lines of code was the measurement, it is likely that the productivity of a 20 person team was overstated.) And then they start to fall further.
If your experience is mostly on teams of 12+ people, your observations about software development will be very, very different than if your experience is mostly on teams of less than 8 people. What works for those types of teams teams is very, very different. And given the huge productivity valley between small teams and large teams, there are a lot of problem areas where the right approach is to maximize what can be done by small teams, rather than to figure out how to build procedures to scale to (the now inevitably necessary) larger teams and code bases.
(If your experience is with larger teams, your first encounter with the potential productivity on small teams can come as a shock.)
// Increment the total
total++;
// Execute our SQL query
var result = query.execute();
Seems to happen a lot with developers who use comments to "sketch out" code (not a bad thing) and then leave the comments in place when the actual code is written.I don't understand this vitriol against all forms of code commenting. (I personally hate the useless, mostly empty function headers forced by some coding standard)
If the comments describe the code this means I have to ignore all comments including those which may be relevant to my debugging. This causes a few specific problems in a collaborative environment.
The first is that the comments get stale/out-of-date/etc, more quickly and are therefore consigned to the archaeology of the program rather than of current relevance. At least with spurious logging, I can take it as a sign that someone had trouble with the code here. With comments I cant even tell if it was done in pseudocode and then translated below. It is useless.
The second is that you can't just add relevant comments into the mess without deleting all the other comments first. Otherwise they can't be sorted out easily or efficiently. In other words, it is worse than useless because it keeps proper, useful comments from being seen or read.
Third, if there are relevant comments there, such as
# This is the maximum value the standard allows for.
Then I won't see these and I am more likely to miss them and hence screw something up by accident.
A better approach is to recognize two things:
1) The code itself needs to be so clear, that you never need any comments for debugging (interface documentation is something very different), and
2) The code plus the documentation together has to be easily readable to the programmer. It also needs to be clear, concise, and avoid duplicating messages any more than needed. Duplication with the documentation of course is required by definition.
I hear a lot of people say they have code they would like to release open source but don't want anyone to see how horrible the code is. The answer is to learn to write code with a dual audience --- human and computer --- in mind. The code comments then function like footnotes would in a text, or as a way for two or three programmers to discuss/debate differences in approach. However, they are not debugging aids.
# print out the value of x prior to increment print("x value prior to increment: %d" % x)
# increment the value of x x += 1
# print out the value of x after increment by one print("x value after increment by one: %d" % x)
// Increment the total
log.Debug("total before increment=" + total);
total++;
log.Debug("total after increment=" + total);
I find myself looking at it and going where is stuff actually happening!I sort of wish someone would allow comments and logging to be combined as language features.
It allows the specially-formatted comments to produce debugging output.
From the synopsis:
use Smart::Comments;
my $var = suspect_value();
### $var
### got: $var
### Now computing value...
# and when looping:
for my $big_num (@big_nums) { ### Factoring... done
factor($big_num);
}
while ($error > $tolerance) { ### Refining---> done
refine_approximation()
}
for (my $i=0; $i<$MAX_INT; $i++) { ### Working===[%] done
do_something_expensive_with($i);
}
[1] https://metacpan.org/module/Smart::CommentsThere is sometimes more to code than readability, unfortunately. I have worked with functions thousands of lines long that can't be broken up without losing a few percentage points of speed - but these functions are called millions of times.
The problem isn't that these comments are harmful (they're not), but that inserting these comments made the coder feel like they'd done their job of commenting their code well, when in actuality the comments provide no insight to why certain things are called or instantiated, or what certain values represent; critical knowledge one needs to extend the code beyond the specific example cases the API guide presented.
----
‘ A for loop iterates through each row of DataGridView
For Each row In DirectCast(Me.DataGridView1.Rows, IEnumerable)
---- Dim frmTakeBackTask As New TakeBackTask
‘ Public oTaskData of TaskBackTask gets populated from the local object oTaskData
frmTakeBackTask.oTaskData = oTaskData
---- ‘ A For loop is initiated to iterate through each child node contained
‘ in the XML document
For Each record In xmlDoc.ChildNodes.ItemOf(0).ChildNodes
‘ A nested For loop is initiated to iterate through each column
For Each column In record.ChildNodesMy beef with "increment the total" comments is not that they are there, but rather that they don't help me get the big picture.
I even find that when I write comments to explain what a specific method is intended for, it helps me avoid violating the single-responsibility principle. If I clearly spell out what I'm trying to accomplish, it helps keep me focused.
To those who say that the code should be elegant enough to be read on its own, there are some cases where the business logic involved is really what needs to be explained. At the same time, what is elegant and concise for you may appear obfuscated and confusing for someone else. You may argue that they should know all the techniques that you know, but that's just the reality of working with others sometimes.
There are good uses of comments, but there are also bad ones. From Coding Horror [1] an example:
'*************************************************
' Name: CopyString
'
' Purpose: This routine copies a string from the source
' string (source) to the target string (target).
'
' Algorithm: It gets the length of "source" and then copies each
' character, one at a time, into "target". It uses
' the loop index as an array index into both "source"
' and "target" and increments the loop/array index
' after each character is copied.
'
' Inputs: input The string to be copied
'
' Outputs: output The string to receive the copy of "input"
'
' Interface Assumptions: None
'
' Modification History: None
'
' Author: Dwight K. Coder
' Date Created: 10/1/04
' Phone: (555) 222-2255
' SSN: 111-22-3333
' Eye Color: Green
' Maiden Name: None
' Blood Type: AB-
' Mother's Maiden Name: None
' Favorite Car: Pontiac Aztek
' Personalized License Plate: "Tek-ie"
'*************************************************
Now imagine something like this exists for every function and you're reading the source code... Annoying.Others are less extreme of course, but repeating the code in comments is bad and even harmful if you forget to update the comment as well as the code. DRY is a good principle to have.
Of course "all comments are bad" is simply wrong, comments are essential to explain decisions or non-obvious snippets or gotchas.
"Object-oriented programming generates a lot of what looks like work. Back in the days of fanfold, there was a type of programmer who would only put five or ten lines of code on a page, preceded by twenty lines of elaborately formatted comments. Object-oriented programming is like crack for these people: it lets you incorporate all this scaffolding right into your source code."
http://www.paulgraham.com/noop.html
[1] I was paid to program in Common Lisp for about 6 years. However, this was a while ago so I was attempting to refresh my memory.
Writing out what you are doing takes a little work, and requires at least briefly thinking about it. It also means you can be embarrassed if your code is doing something irrational or unintended, and looking at everything again when you make major breaking changes.
By Occam's Razor, it seems more likely that complaining about comments is driven by an unwillingness to produce them more than actual practical problems created for others by their presence.
It's nice to have a brief description of what a class (or in many cases, a method) is intended for, etc. As others have said, it saves time each successive programmer from having to fully understand all of the source code.
* Returns the name
* @return the name
*/
public String getName();The net gain is that you get nice API documentation. The downside is that you have a verbose and obvious comment in the source.
Given that reality, I would rather forego the comments for readable code. Readable code tells me what is going on, and doesn't lie!
Nor when jackass(B) updates the code and not the comments, making them misleadingly worse than no comments at all.
But when the code now has to be maintained by programmer (C). This means you.