9 ms·
Stop commenting your code just to say you did
- ef4 13y agoThis is one of the reasons that programmers who haven't read much of other people's code are a liability. They're as lost as novelists who don't read books. The difference comes down to empathy: if you can get inside the head of your future readers, you'll know when to comment, and what to name that function, and how long the functions should be, etc...
- pekk 13y agoSo can we say the same about people who try to lobby everyone not to use any comments just in case they might be wrong? Because a helpful comment can be a very helpful thing to a reader of code
- nghst 13y agoI think the occasional "header" comment is useful, even in cases where the code is obvious, i.e. // do blah blah obvious_thing; obvious_thing; obvious_thing; obvious_thing; // do something else obvious_thing; obvious_thing; obvious_thing; obvious_thing; Even though none of the lines really need documentation, having the comment ensures that you can quickly jump in when you come back later. This is really useful in something like drawing code.
- wdewind 13y agoHere's a better solution: function main() do_blah_blah(); do_something_else(); end function do_blah_blah() obvious_thing; obvious_thing; obvious_thing; obvious_thing; end etc..
- jeremiep 13y agoIt should be pointed out that with inlining, both versions are exactly the same at runtime. Descriptive function names never lie, comments often do.
- masklinn 13y ago> Descriptive function names never lie Beg pardon[0]? function _utf8Encode(&$arr){ for($i=0;$i<(count($arr['parameters']));$i++){ $arr['parameters'][$i]= $arr['parameters'][$i]; } } function _utf8Decode(&$arr){ for($i=0;$i<count($arr['parameters']);$i++){ $arr['parameters'][$i]= $arr['parameters'][$i]; } } Or[1] public static string ReturnEmptyStringIfNullElseValue(string value) { if (value == null) { return ""; } else { return value.ToString().Trim(); } } [0] http://thedailywtf.com/Comments/There-and-Back-Again.aspx http://thedailywtf.com/Comments/There-and-Back-Again.aspx [1] http://thedailywtf.com/Articles/Common-Functions,-not-Common-Sense.aspx http://thedailywtf.com/Articles/Common-Functions,-not-Common...
- jeremiep 13y agoI stand corrected. Thank god I never have to deal with such code!
- wschroed 13y ago> Descriptive function names never lie, comments often do. Description function names lie just as much as comments. For example, I have run into cases in the wild where things like "get_item()" create database entries before returning a value. Yes, side effects are evil, etc etc, but the point is that at some point, somebody maintained the code and did not update every use of get_item() to now be get_and_or_create_items_if_it_is_sunday(). In rare cases, I have seen them at least update the local documentation.
- collyw 13y agoWhat's to say a function gets "fixed" without updating the name, in the same way that comments will not get updated? I see it would be less likely in a function, but not impossible.
- fournm 13y agoThis isn't always possible in every case--it's not too hard to imagine a lot of trivial assignment all going on at once, that isn't immediately obvious what it is or why on earth it exists. //really bad example, just something really repetitive function main() // set up month boundaries janStart = blah; janEnd = blah; // ... decStart = blah; decEnd = blah; end where it's not too hard to imagine many languages without great pointers needing to keep that inline to avoid making all of those variables global. In some (hopefully most) cases just better design in general can get around it, but I wouldn't always count it out immediately. edit: oops, formatting fail.
- zimbatm 13y agoAnd now you have three places to look at instead of one.
- wdewind 13y agoHow do you figure?
- raverbashing 13y agoYes If you write this: x = 1; // sets x to 1 I HATE YOU Explain the WHY not the WHAT It's the same crap with the Hungarian notation, where half MS didn't get how to do it properly. It's not the computing type, it's what the variable represents. Thank you, I know this is an int, the compiler knows it's an int. What I need to know is what this is counting/representing/etc
- yk 13y agoThing is, just like with code, you write good comments by throwing away bad ones. The writing of the bad ones is not optional.
- carsongross 13y agoGod forbid someone gets their thoughts together with comments outlining what a function is going to do and then fills in the code... Or, while deep in thought, someone taps out a bit of redundant commentary on a line or two of their code... Or someone needs a bit of natural language to provide an anchor in their code. The important thing here, I think we can all agree, is that we are smarter than that person.
- deleted 13y ago[deleted]
- ebiester 13y agoNot at all. I use comments like this frequently. It might even be checked in while development is happening. However, the "whats" are taken out completely - the tests are better places to figure out how it works, anyway. The "hows" are mostly taken out -- if someone needs to know how it's working, it needs to be refactored. (And that's why I wrote the tests!) What remains are the "whys." Why was this algorithm chosen? Why does this look seemingly broken? Why is this code here? (IE, performance improvement led to a little less clean code.)
- swanson 13y ago// don't use hardware acceleration canvas.enableHardwareAcceleration(true); Which is true? The comment is lie. Is this a bug? Was this changed for some reason? Should I remove the comment? Should I toggle the boolean? Why weren't we supposed to use HW acceleration? Why are we using it now? What changed? What value did the comment have in the first place?
- Ellipsis753 13y agoIt's a pain but check the git history.
- swanson 13y agoBoth lines were committed at the same time in a changeset with 15 other files. What now?
- Danieru 13y agoI suspect part of this is enforced by TA markers in university. When marking a TA isn't trying to understand the code, they just do not have time for that. So when evaluating the documentation or comments portion of the mark they just scroll through and see how much gray is on their screen. No marks are ever deducted for bad comments. The situation can get so silly I've had TAs complement my code and the design then deduct full documentation marks. This has led some people I know to go over their code before submission and add worthless comments. To them "documentation" is a separate step which occurs after you've written and tested everything. The whole situation is a shame.
- lmm 13y agoIt's not just markers at university, I've had managers who would do the same thing.
- hjnilsson 13y agoWorking as a contractor, there are often deals that mandate "100% of functions documented" or other silly stuff (I would never strike such a deal, but have inherited projects with this). Since the client actually never checks the code (only metrics) and will never pay what it would cost to create amazing documentation (which only makes sense for public APIs) we just end up with tools that automatically adds comments to functions, which means the codebase ends up with useless javadoc-like clutter. It's the same with "100% test coverage", which is similarly abused, programmer's are a lazy bunch, and smarter than any tool that measures the quality of what they do. So forcing them doesn't work out great.
- untog 13y agoWorking as a contractor, there are often deals that mandate "100% of functions documented" or other silly stuff I'm not so sure that's silly. It's absolutely overkill, but in a contractor/client relationship it makes sense that the client will want to make sure they have all the coverage they can get. And as a contractor you can bill for it.
- 13y ago
- deleted 13y ago[deleted]
- logfromblammo 13y agoMy current employer makes the useless code comments mandatory. They do not need to make sense or be useful; the requirement is that they exist. Fortunately, they pay me enough that I am not looking for other jobs over it. No, I'm looking elsewhere due to the many other aggravations that are not worth the salary. Not only are businesses training younger developers to do this, but they are training older developers to expect it. Of course it is going to bleed over into the real world.
- pekk 13y agoIf they were paying you in part to make adequate documentation (which might well include good code comments) I wouldn't see any problem
- logfromblammo 13y agoIt is a Cargo Cult Code Convention. Good code has documentation, therefore our bad code will become good by adding documentation. Truthful comments, such as the following, would likely get the writer fired and not improve the code one little bit. /* This code block is a crufty, kludgy crock of dung. I have argued several times that it represents a morass of technical debt, security holes, and degraded performance, but I have so far been explicitly denied permission to fix anything in it. In addition, it is so tightly coupled to equally bad code that it is impossible to test easily. But now the good news. If you can stand to look at it, this code will pay your mortgage, and the mortgages of 20 other people, because your bosses have more money than brains. / Instead of writing that, you get this. / Magic. Edit this code at your own peril. */
- SomeCallMeTim 13y agoThe example that he gives that I take issue with is the "Constructor" one in a JavaDoc comment. When using documentation tools, every undocumented function spews a warning. And that is as it should be. But some simple constructors don't have any functionality worth documenting. I code as if all warnings should be addressed, and that's true of my documentation generation. If a public function has no documentation, that should be considered an error that needs fixing. If the documentation is obvious, then so be it. That is the price you pay for reliably good documentation; without enabling those warnings you don't know when you've missed documenting an important function. And even sometimes the "obvious" is useful; I don't know how many ambiguous Boolean parameters I've seen where it wasn't clear what value "true" represented.
- mjmahone17 13y agoIf you're only documenting after the fact, your function isn't worth documenting: it means you conceptually understood it well enough that you didn't have to think much about it's inputs or outputs. If you did have to think through it, or your code reviewer doesn't understand it, add a comment explaining it. In any other case, commenting on it is probably useless and adding to clutter. Javadocs are painful to read, not because it's a bad idea, but because so often it's things like "toString(): returns a string that is the string of this object". Sorry, I only need to know that function exists and it's return. I want to be able to scan through and see only those functions that are conceptually strange or unique, not the boilerplate that every class has to have, and is identical. If there's a comment on the toString() function, it had better be documenting something interesting, or else it's more useless than nothing.
- SomeCallMeTim 13y ago>If you're only documenting after the fact, your function isn't worth documenting I can't disagree more. You can completely understand what you intend as you're writing a function, and then later, as you look back with a fresh perspective, realize in what way(s) the function could be misunderstood. >Javadocs are painful to read, not because it's a bad idea, but because so often it's things like "toString(): returns a string that is the string of this object". Straw man. "Bad docs are painful to read." Sure they are. If you have good documentation practices, you'll explain in toString() HOW the object is represented. "Return A string that indicates the (derived) object type, its x,y coordinates, and its current state, along with any additional state specific to the derived object type. You should not rely on its precise format, as it may change in the future." The real problem is that most documentation sucks. But the only way that developers will ever get better at documentation is to practice. I also am confused as to why "scanning" JavaDocs would ever need to be a thing; you do end up with your JavaDocs as a web page or help file, right? If I'm confused about a function, I want to be able to click on it and see docs; if there are no docs on half the functions, that's a failure of the imagination of the API author(s). If they can't see how someone might be confused, and yet I'm confused, then they blew it.
- quackerhacker 13y agoComments in production code have always been a pet peeve of mine. I understand the OP's frustration on useless comments where the function clearly states enough in it's naming convention. I brought this up to one of my instructors before and he said that comment overhead is negligeble on bandwidth (I was referring to css and js commenting at the time), but I don't think that's true when you factor in mobile networks and when some teams comment every freaking line when naming convention and common sense should suffice.
- fournm 13y agoI would hope that you would be using minify in some way, which lets you still have your comments and just drop them for production.
- millstone 13y agoDon't listen to this guy. Copious comments are great. 1. They act as a easier-to-skim narrative of the code. You can often get an outline of a well-commented component by reading the comments alone, rather than by picking apart a language designed for machine consumption. Syntax highlighting makes this especially easy. 2. They're helpful for other programmers who may not be as comfortable in the language as you are. For example, my PHP is about ten years old; I had no idea that `__construct` is the constructor, and not just another function. But thanks to the "useless" comment, I do know that. 3. They're helpful for programmers who aren't as comfortable in the problem domain. A line in a FFT implementation may be "obvious" to those skilled in harmonic analysis, but not the poor client programmer who is trying to figure out why the function is returning garbage output. 4. They can be useful as a thing to search for when you need to navigate around. When deciding if I should write a comment or not, I ask myself a simple question: if I come back to this bit of code, will it be obvious why it’s been written this particular way? If my future self will be very thankful for an explanation, then it’s a no brainer, I write the comment. Note the assumption that the code will only be consumed by "my future self". Ever maintained someone else's under-commented or no-commented code? I'm sure the original programmer did not have any trouble with it, and will never know what he inflicted on his successors. Spend some time working in a comment desert, and you'll never complain about the rain.
- swanson 13y agoDon't code for machine consumption, code for programmer consumption. Code is read 5x more than written, etc. Use function/method/class names that are readable like an outline. Code comments are a poor teaching tool. Use a coding style guide/standard, pair programming, training, or a book to teach basic language idioms. I don't buy the "searching argument". Ctrl+F for "account" will match a method named "lookupAccount" just as well as a comment that says "//lookup account". If you use a somewhat consistent naming scheme, it will probably be easier to search for something - try finding more than 2-3 words in a row in prose. Putting so much perceived value and trust into code comments is like trusting "Architecture Design.docx" instead of looking at the actual running code.
- mattfenwick 13y agoIf "copious comments are great" is true -- does that mean we should write copious comments? I'm talking about opportunity cost here -- the time spent writing comments is time not spent on the code, design, test, etc. So for me the question becomes what I should do to provide the max benefit for the least cost -- should I write comments, improve the design, fix up some code to eliminate special cases, test for corner cases? Since it's an inherent trade-off, I don't see this as being an easy question to answer. Probably, there are multiple adequate answers.
- whyme 13y agoI'll suggest there's a missing ingredient here...I found I was able to eliminate many of my comments by asking myself if that someone whom might read my code would be better served with a unit test instead. I also found, however, that this needs to lead to an understanding that unit test are in fact a form of documentation and should be treated as such.
- millstone 13y agoIt's a great point that, if there's some behavior worth capturing in a comment, you may also want to capture it in a unit test. But why should you strive for the "ability to eliminate" comments? What is the advantage of having fewer comments?
- whyme 13y agoI subscribe to the minimalism approach. i.e. I do my best to improve the signal to noise ratio (which is inline with the authors goal). Also, in many cases, having a both the unit test and the comment is a redundancy.
- jgrahamc 13y agoLeaving comments in real life: http://blog.jgc.org/2011/11/leaving-comments-in-real-life.html http://blog.jgc.org/2011/11/leaving-comments-in-real-life.ht...
- Aardwolf 13y agoFrom the article: "One day, I suppose, it'll be possible to use an app-for-that, to leave virtual notes." WHYYYYY? Physical notes are much better! They'll be there forever, while the app would be a temporary fad.
- apdinin 13y agoI can agree with the seeming intention of the OP, but the analogy of adding labels to wires in an electrical box is problematic. How does having blank labels on wires equate to poor commenting? Good or bad, a comment says something about the code it's commenting (even if the code is self explanatory). A blank label says nothing about the wire. The better analogy might be having labels on wires that state the color of the wires -- red, blue, green, etc.
- beshrkayali 13y agoNot that I don't agree, sometimes unnecessary comments kind of make it a bit complicated to understand what's going on. BUT, an important point to mention is that coders write code in different styles and manners, there is no right and wrong when it comes to comments. Sometimes just seeing that comments exist (even if some lines are pointing the obvious) makes a difference to the inexperienced or to the new-comers. Not to mention that "obvious" here depends heavily on the experience of the developer with language, framework, or whatever they're using. I guess the person writing the code should at least get to write comments the way the like. You're a programmer, reading a couple of extra comments won't ruin your day, just skip it if it's obvious.
- err4nt 13y agoI'm beginning to believe that if code is simply a machine-interpretable codification of human expertise, then we should be able to express precisely what the code should be doing using written language as well. I've been turning this over in my head to figure out how it should look in practice, but I'm wholeheartedly believing the following statement is true: "All code should be composed in two languages: first in whatever programming language the task requires, and second in whatever language the programmer speaks natively."
- err4nt 13y agoI guess an extension of what I mean is maybe we should write our comments in a way that a human could read a program like a set of how-to instructions, complete the same operations, and arrive at the same result interpreting your work in written language as the computer would arrive at running the code. In my way of thinking about things, code wouldn't be complete until it could be interpreted by man and machine equally. This allows for the preservation of our human expertise by guaranteeing that any program can be translated in the future by another human reading the same written language into any other programming language (even if they can't understand your code). This could be important especially for some of the more exotic languages with sparse documentation today, imagine what it will be like trying to decipher these things in 200 years!
- icehawk219 13y agoOne of my guiding principles for code comments has always been "say why not what". If I can't figure out that what on my own then something is probably very wrong with the code. What I want to know is why you used a for() instead of a while() to iterate over an array or things like that. Comments that explain what you're doing I find to be cruft. I don't necessarily hate on them but I do find them unnecessary and unhelpful.
- kephra 13y agoI've learned coding in Forth, so my code is often creating a domain specific language to solve a class of problems, and Forth shadow pages caused the documentation to be roughly same size as the code itself. But I normally comment in manual style. So the comments in my code do not tell how it works internally, but how to use it, and they are extracted from the code to create a standard Unix roff manual page. I think the Perl community did a good job in constraining a documentation style that is useful for those who want to use a module. There are seldom exceptions, where I actually comment the code itself. Those are clear warnings that this code is not trivial to understand for average programmers. E.g. my w3dig search engine implements a recursive descendent parser for the site description language, that is not always executed linear, but sometimes pushes a parser class instance together with a closure to a queue, for parallel execution of the spider.
- dmckeon 13y agoComment first: project the document instead of documenting the project. In other words, write the comments first, then write the code, then review and tidy up both the code and comments. By writing the text first, you clarify the why before you write the how. You also capture the high-level view before you get down to the gnarly details, after which the high-level view can become a vague ghost of a memory. Once that high-level view is left behind, many people become so immersed in the coding details that "introductory" material written after coding often begins with the esoteric details of the implementation of the central algorithm, and fails to mention what the tool/packages/code/app is for in the first place. To put it another way, documenting is to code as foreplay is to sex. Both code and sex can be effective without comments or foreplay, for some values of effective, but they are more likely to be more pleasant and repeatable over time if people put in a little time and effort before rushing ahead to what they see as the most interesting parts.
- methodover 13y agoI cannot recall a time in my career as a programmer where the inclusion of a comment has caused me serious problems. However, I can recall many, many times where I've read code that does something odd, and wished that there was some documentation explaining it. I've met many programmers who rarely comment and make points similar to those made in this article. It's an easy argument: code should be self-documenting. But I've seen too many programmers jump from "code should be self-documenting" to "I shall never use comments/docstrings." I feel like the problems outlined in the article are overstated. It really isn't a big deal when you read a comment that doesn't make sense, or is empty of content. It's a much bigger deal when you read strange code which really deserves documentation but there is no documentation.
- shearnie 13y agoEqually frustrating are revision comments (usually for a big end-of-day commit) that go: "Committed changes".
- korzun 13y agoTo author, the constructor is not a function it's a method. I agree with useless comments but don't agree with blank 'constructor' method doc blocks that just say constructor as a filler. Since most of the methods will have params/returns and better description than a simple constructor, leaving constructor without any doc-block is kind of counter productive and silly.