10 ms·
>Comments are for the weak, Care to elaborate on this ? Commenting code is bad ? Or did I miss the irony ?
by nickolai 14y ago
>Comments are for the weak,
Care to elaborate on this ? Commenting code is bad ? Or did I miss the irony ?
- recycleme 14y agoI've met a few senior level programmers who frown on detailed commenting (or commenting at all). I cannot wrap my head around this since I consider it best practice to comment. 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.
- wreckimnaked 14y agoThere's some debate on this: http://queue.acm.org/detail.cfm?id=1053354 http://queue.acm.org/detail.cfm?id=1053354
- creativename 14y agoI feel like there are some people who go overboard on the formalities of commenting (specific format, etc.), but in general I can't think of one instance where I've thought "man, I wish I (or someone else) hadn't spent time explaining what this does". 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.
- lawn 14y ago> I can't think of one instance where I've thought "man, I wish I (or someone else) hadn't spent time explaining what this does". 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.
- creativename 14y agoYeah, that's exactly the kind of formality and over-commenting that I meant by "I feel like there are some people who go overboard on the formalities of commenting (specific format, etc.)". I saw a lot of examples of that at my old employer where they had tried (and failed) to automate some of their documentation years and years ago. 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.
- lawn 14y agoAh I see, misunderstood a bit.
- arethuza 14y agoReading this discussion (and posting a comment about s-expressions) got me reading about Lisp[1], and then wondering about contemporary Lisp implementations, and then to Arc where I found this amusing comment by our host: "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 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.
- slurgfest 14y agoWhat is interesting about reading this discussion is that all of the 'examples' used in order to show that comments are bad are totally implausible. On the other side, the situation of 'no comments at all' is actually ubiquitous, in reality. 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.
- deleted 14y ago[deleted]
- arethuza 14y agoI tend to get a bit upset if code has comments that basically just describe what code is doing rather than why. Stuff along the lines of: // 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.
- flatline3 14y agoI prefer code where I can skim the comments and see the major plot points, at a glance.
- dllthomas 14y agoIf you need to skim the comments to see how a function is doing what it's doing, the function is too long.
- flatline3 14y agoWhen it can take 3-4 statements to perform a single logical operation, there is still value in summarizing each block with a comment, even if the function isn't "too long".
- gnaritas 14y agoThat's what function names are for. Comments don't need to summarize. A useful comments says why code is this way, it doesn't summarize or repeat code.
- flatline3 14y ago> That's what function names are for. A single function for every 3-4 line operation would result in incredibly disjointed code, and would require more explicit documentation of invariants because that function can now be called elsewhere (at least inside of the given translation unit). > A useful comments says why code is this way, it doesn't summarize or repeat code. That's nonsensical. Why wouldn't you want to abstract the complex?
- flatline3 14y ago> I've met a few senior level programmers who frown on detailed commenting (or commenting at all). 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.
- randomdata 14y ago> that would otherwise require each reader of the code to understand the code itself in depth. 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?
- flatline3 14y ago> Is that a problem? 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.
- julsonl 14y agoThe issue I have with commenting is some people enforce it for the sake of having comments in place, which would most of the time describe the "what" and the "how" of the code, rather than the "why", which in my opinion, where most of the value lies. In Java, the usual offenders would be the getter and setters in POJOs, like: * Returns the name * @return the name */ public String getName();
- flatline3 14y agoComments like that exist simply to appease documentation tools that can't derive those comments automatically. The net gain is that you get nice API documentation. The downside is that you have a verbose and obvious comment in the source.
- slurgfest 14y agoAren't such comments usually autogenerated by the IDE or such tools?
- ucee054 14y agoThe problem is not when programmer (A) writes the code and the comments correctly. 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.
- wanderr 14y agoThe only thing worse than uncommented code, is wrongly-commented code. In my experience, code is almost always wrongly-commented, either because the programmer wrote the comment wrong in the first place, or because they wrote the code wrong, or because the code was later updated to do something different, and the comment was not updated to reflect the changes. In my experience, especially in an old codebase, it's extremely rare to find a piece of code that is both thoroughly and accurately commented. Given that reality, I would rather forego the comments for readable code. Readable code tells me what is going on, and doesn't lie!
- einhverfr 14y agoIn my considered experience, those who are most hostile to unnecessary comments tend to put the most comments in their code. It isn't an argument against code comments, just being very picky about what is a useful comment collaboration-wise.
- sunwooz 14y agoMaybe he's saying, if your code is simple and elegant enough you won't need to comment.
- flatline3 14y agoThis is a fable bad programmers tell to themselves to justify their intellectual laziness. 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.
- rimantas 14y ago> 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…
- flatline3 14y ago>> 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... sendDataWithTimeout(user_t *user, data_t *data, time_t timeout); What happens if delay is 0? Can user be NULL? What happens if it is NULL? How large can 'data' be? Is there a limit? Will the send be chunked into multiple dispatches if 'data' is too large? Is that opaque to the caller? Does it matter to the caller? If none of those questions are answered, the caller must delve into the sendDataWithTimeout() implementation to figure out the answers, and it is impossible to modify sendDataWithTimeout() without possibly breaking assumptions callers make based on what they've assumed from implementation of sendDataWithTimeout(). This applies equally well to blocks of code within a function that accept input and provide output. It helps to be able to reason about them as atomic units, without necessarily paying the code/maintenance cost of hoisting them into independent functions.
- anusinha 14y agoA bad comment can waste a lot more time than the absence of a comment or a useless one (like x += n; //add n to x).
- timo614 14y agoI'd say build your code such that you don't need to comment but comment wherever there is some unclear reason for why something is done. 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.
- electrograv 14y ago> 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.
- timo614 14y ago
- le-manchester 14y ago>Don't become the old people you hate, always try to learn new things, no matter how alien. So following that: There's a good talk about Code Documentation: http://www.youtube.com/watch?v=tCw7CpRvYOE http://www.youtube.com/watch?v=tCw7CpRvYOE
- FuzzyDunlop 14y agoI think it could be summarised as thus, in general terms: 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.
- DannoHung 14y agoWe could probably resolve this aspect of the argument by teaching novices that a perfect/great/accurate/otherwise-superlative name(s) is better than almost any comment.
- le-manchester 14y agoNot at all because programming languages like Ruby parameter names don't tell the full story: if you have def find(name) what kind of type could be name? String "Steve"?? Symbol :Steve? Hash {:first => "Steve", :last => "Jobs"} ??
- aneisf 14y agoThat just means that 'name' is a poor name for the parameter. Have 'first_name, last_name' or 'full_name' or 'names,' for example. In addition, I think it's a good practice to get into to try and validate parameters at the top of any method. If the values don't fit your use for them, raise an exception.
- donall 14y agoThere's a lot of back-and-forth in this discussion already and I feel like some people aren't understanding that it's not about _never_ commenting the code; it's about only commenting when it is absolutely necessary (which is actually quite rare if you're writing clean, simple code (which is, itself, quite rare!)). 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_Handbook_of_Agile_Software_Craftsmanship.pdf 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).
- einhverfr 14y agoThe key things are: 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.