by tokenizer · 14y ago · 0 comments
My version of the list. This was fun!
Care to elaborate on this ? Commenting code is bad ? Or did I miss the irony ?
You should never need to write a comment to explain what you're doing. If you feel you have to, rewrite the code until it doesn't need explaining in a comment.
# this method manipulates dimensions
def method_x(a, b, c, d)
# a is the width
# b is the height
# c is the depth
# d is a list of options
...
end
That could obviously be re-written as: def manipulate_dimensions(width, height, depth, options)
...
end
However, it may very well be the case you have to explain why some code exists, or why it wasn't done another way: def post_to_awkward_api(data)
# stupid.io doesn't accept HTTP Post params
# so we have to use a comma separated string
silly_string = data.join(',')
....
end
def bug_fix_workaround
# see http://stackoverflow.com/relevant-question/...
end
Not that my examples are amazing. But there'll always be the case where another developer (or even yourself) is not privy to the thought process that conceived a particular block of code.if you have def find(name) what kind of type could be name? String "Steve"?? Symbol :Steve? Hash {:first => "Steve", :last => "Jobs"} ??
Also I would say that not all comments are created equal. You comment your API's first, then implement/explain them with code, then describe why with more 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.
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?
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.
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!
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
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.
// 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.# 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)
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.
* 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.
I think that everybody should be required to read the chapter about commenting in "Clean Code" before contributing to this discussion. It's very java-centric and not perfect, but there is some really good insight. There is a pdf available here: http://www.tud.ttu.ee/material/kallik/JOOP/Clean_Code_-_A_Ha... (if it really helps you, consider buying a copy and supporting the authors).
1) The code should speak for itself, and
2) You comment when you have something to say outside of what the code says.
Chances are, ironically, if you stop using comments as a crutch, you will use them more often because they will start to be a useful tool.
No real world code is simple and elegant enough that you don't need to think through the complex invariants of the code, consider would be relevant to future maintainers, and then write it down.
> This is a fable bad programmers tell to themselves to
> justify their intellectual laziness.
No, actually commenting is easier solution for the lazy ones. Too bad they are to lazy to update the comments when something changes. > No real world code is simple and elegant enough that you don't
> need to think through the complex invariants of the code
Oh, please…in my experience working on enterprise biz apps the opposite is true. comments are what you do when you don't have time to make the code explicitly match your mental model of the proper solution. "don't have time" is a bit of a euphemism, as a lot of people don't realize that it is possible to write code that explicitly matches our mental model of the solution, but whatever.
here's an example: python lib requests vs urllib2. one of these could probably use a comment. the other is self evident. https://gist.github.com/973705
Unless, of course, you write in a functional language like Haskell. All those invariants become explicit and your code magically becomes simple
The code most of us write is a hodgepodge of business logic, frontend code, and a bunch of glue to make it all work together. In the case of business logic context is highly important. Just looking at the code doesn't convey the whole story or the "why" this code does what it does. In this specific case comments are the difference between saying "we don't know why this works," and "according to BUG-#### we need to send the counterparty this field as a logon credential otherwise their system behavior is undefined."
Instead of x+= n; running_total += total;
But comments are helpful for understanding the reasoning behind why something was done.
For example: $.resize.delay = 16;
Was placed in one file of some code I collaborate on with the comment "// this is probably a horrible idea"
I had to ask the developer what exactly the code does (yeah I could have looked it up but since he said it was a horrible idea I wanted to know why). Turns out it just configures the jquery resize event to fire at about 60 frames per second.
Having a comment like: // Configures jquery resize to fire the resize event approx 60 frames per second
Would have made the code a bit easier to understand.
I'd argue that the following line is a better solution in every way than adding a comment as you suggest:
setResizeEventFireRate(60); //just pseudocode of course
Self-commenting code is always better: less duplication, less maintenance, greater refactoring agility, and most of all, it encourages you to design a cleaner system in the first place.Granted, in real-world scenarios, there will always be many cases where you are forced to add comments, sometimes extensively (hand-optimized code, inherently complex systems, etc).If anything though, this only confirms how important it is to aim for self-documenting code.
Real-world production code is rarely a pretty thing, and the fact that you have to start adding comments everywhere is a reflection of this. You'd be surprised how clean and elegant code becomes when your only goal is to make it as self-descriptive as possible.