7 ms·
Why aren't you commenting your code?
A refresher on some of the major benefits of commenting throughout your code. Meant to serve as a reminder for those still struggling to make it a habit.
- apathetic 14y ago// It was hard coding it // so it should be hard reading it
- joshbaptiste 14y agoAnyone have an example of well commented source code?
- wulczer 14y agohttps://github.com/postgres/postgres/blob/master/src/backend/optimizer/util/clauses.c#L3574 https://github.com/postgres/postgres/blob/master/src/backend... In general, most of Postgres code.
- d23 14y agoAt first brush those comments seem overly verbose and obvious: /* Do we have any named arguments? */ ... /* If so, we must apply reorder_function_arguments */ if (has_named_args) { args = reorder_function_arguments(args, func_tuple);
- noselasd 14y agoThough I do appreciate comments such as this: /* Fetch the function body */ tmp = SysCacheGetAttr(PROCOID, func_tuple, num_pg_proc_prosrc, &isNull); Newcomers have be be quite familiar with the internals to immediately see that the line fetches the function body.
- deleted 14y ago[deleted]
- Retric 14y agoI prefer a far more stilted comment style otherwise you have trouble remembering the code between the comments and tend to scroll a lot more. I mean /* The error cases here shouldn't happen, but check anyway */ is really not that helpful. Also, all the long descriptions before function calls are mostly redundant. If i want to know what a function does I can go there and look, but it really should have a sufficiently descriptive name that after the first time I don't need to check again most of the time. Unless something non obvious is going on.
- wulczer 14y agoI think it is helpful to know if the check is just a sanity check or if there's an already known set of conditions can lead to that particular error. The function comments I also find very useful. Read a few of them and see how much information they carry. Preconditions for the function, reasons why it does what it does, assumptions it makes... These functions are used from throughout the code and it's important to document them well. I'm purposefully not quoting specific parts of the file, because of course if you look at each and every one of them, you'll find a few that could be improved. But the OP asked for a well commented code base and if PostgreSQL is not one, then I don't know what would be.
- Retric 14y agoI could argue that comments are best for exceptional behavior so if it's normal to do a lot of sanity checks there is little reason to comment on each one. However, my point was saying something like: if (error) //sanity check Saves space and get's the same point across without padding the line count.
- plorkyeran 14y agoI actually rather like that comment. When reading code I find it useful to figure out how each error condition can be hit, so it's nice to know that something is just a sanity check and shouldn't ever actually happen.
- cdoxsey 14y agoPretty much all of the Go standard lib. http://golang.org/src/pkg/time/time.go http://golang.org/src/pkg/time/time.go
- ams6110 14y agoThe thing about comments is that they don't get maintained. So the comments end up diverging from the implementation. The tests all pass even if the comments are wrong, so nobody cares unless you are particularly diligent about code reviews of EVERY commit. Also this should go without saying but I still see comments like this: // loop over the collection for (var foo in bar) { ... } which are not helpful and just clutter the code.
- robmcm 14y agoIt's often said, "A comment is a lie waiting to happen".
- InclinedPlane 14y agoIt's a huge anti-pattern, because then people train themselves to think that slamming out a lot of trivial and redundant comments is a good use of their time. Worse, then they get used to writing lots of trivial comments and the really important more complex or subtle comments go unwritten.
- wulczer 14y agoBad comments are like bad tests, they're bad. Good comments, like good tests, are a boon for complex software.
- seanmcdirmid 14y agoA test will at least fail when wrong, a bad comment will just be confusing.
- robmcm 14y agoYou shoudl read Robert C Martin's, "A clean coder". http://www.amazon.co.uk/Clean-Coder-Conduct-Professional-Programmers/dp/0137081073 http://www.amazon.co.uk/Clean-Coder-Conduct-Professional-Pro...
- attheodo 14y agoAs mentioned in Clean Code, beautifully and concisely code doesn't need much of commenting. It's pretty much self-explained.
- Evbn 14y agoAnd over here in the messy real world with weird dependencies and legacy junk and performance-critical regions, we have comments.
- espinchi 14y agoSometimes documentation is just a way to (try to) make up for poor code. I usually pretend I can't document my code while developing. I'll sure add some anyway. This doesn't apply to public APIs. There, you of course need to be more explicit.
- pgsandstrom 14y agoCommenting methods can often be redundant. But I find it is almost always a good idea to comment classes that contains any degree of complexity. Too often when digging into a new project I see a class like "ItemHelper", and have to read a few dozens of lines to realize something that could be summarized like: "Converts X-data to a format that Item can parse". It makes it so much easier to get introduced to a code base, and comments like that seldomly needs to be updated.
- da_n 14y agoYeah, but what about // $set $foo to $bar $foo == $bar; // print out value of $foo echo $foo; // is $bar the same as $foo? if so, return true, otherwise return false if ( $bar === $foo ) { // check if the same return true; // great, it's true! } else { // here we check if it isn't true return false; // nope, not true, let's return false } I have nothing against comments where something needs to be documented, but not everything needs comments as most code is essentially self-documenting. Edited for clarity.
- andreasvc 14y agoIt's completely uncontroversial that those comments are unnecessary. When you see them you remove them; no reason not to write any comments at all.
- sethetter 14y agoI expected it to be a given that these kinds of comments are unnecessary. It's better to comment on the "why" than the "how" or "what". Comments are useful when they help explain a piece of code's integration into the rest of the system. Why is it there in the first place?
- InclinedPlane 14y ago99% of the time when you are writing a single line comment you should instead be either renaming a variable or using the extract method refactoring using some abbreviated form of the comment in the new name. For the remaining cases it's more important to make sure that you're documenting the "why" of something in the code. If you find yourself often in the situation where making changes to the code requires modifying the comments to keep them up to date that's a big sign that you aren't writing comments appropriately.
- Evbn 14y agoComputeGeometricMeanPriceChange2YearWindow. There is something to be said for the spacing that comments allow.
- InclinedPlane 14y agoStart there, then continue refactoring and renaming. I've rarely run up against a situation where an unwieldly long name was actually irreducibly so.
- kbenson 14y agoI find comments useful in two main cases: 1) When I'm not all that familiar with the language. This allows me to grok the purpose and actions of code quicker. 2) When the action being performed contains more lines than fit in the screen. Knowing a bit more context going in can make what follows more clear. For 1, it's a matter of who you intend to read/modify the code after you. For 2, that's probably more a case for splitting that code into multiple functions. From that, I think comments are best used by poor and great programmers, but the middle of the road may not get much benefit out of them. If you don't know how to split your complex bits of code into multiple chunks, or if you expect most people coming after you to now be as experienced as you, comment.
- swanson 14y agoComments - like documentation - are a liability. Most projects tend to treat them as supporting artifacts, but they are actually unidentified risks. Did you account for the time spent either rewriting documentation/doxygen/comments as you go (frequent chunks of small work) or an after the fact round of document backfilling (single chunk of large work) in your schedule? No one even reads those documents. The client claims they are to assist future developers - internally or another vendor - but would you trust a Word document or a .cpp file when everything is on fire and you need to figure out a system's behavior? Same thing applies for code comments. There is one source of truth in software, the code. You can pile on the design documents, wikis, and architecture diagrams but at the end of the day, what is coded is what gets executed. Make the code easy to understand and reason about. And then, if you really want to be nice to future developers, throw in a single page overview of the codebase (README) that gives someone an entry point. Edit: I will just add the caveat to preempt the inevitable - this does not apply to public facing documentation of an API/framework/library etc.
- seanmcdirmid 14y agoThis. Comments and documentation are pointless unless they are audited and vetted somehow, then there is the extra cost associated with maintaining them. Managers who don't know better think its just a bit of extra work that the developer does up front, but that is pointless without the above.
- leothekim 14y ago"There is one source of truth in software, the code." I agree with this statement wholeheartedly. Documentation starts with readable code. Comments can go out of date and, worse, lie to you.
- cobrausn 14y agoNot all code is readable. Some of it always ends up being an ugly hack. If that ugly hack is not documented, I want to start punching previous developers. I wish people would stop taking these purist approaches. There is an obvious middle ground to this - document the non-obvious and your public facing APIs.
- niggler 14y agoI started writing code in a more literate style recently (where the code is a document with markdown interspersed with the code segments) and found that writing what I want to do first makes the development process much easier than just delving into code. Feels like writing a paper in many ways (you write the outline, flesh with your thoughts on how it should work, and then start writing code) I put this tool together on a whim (although the github rendering is somewhat strange because I took liberties with the fenced code blocks): https://github.com/niggler/voc https://github.com/niggler/voc
- dicroce 14y agoI think the next level for you is to do the thinking before coding that your doing now, but just skip the commenting part...
- niggler 14y agoI used to plan in my head / on whiteboard, but that doesn't scale well when you want to start handing code off to your employees.
- Evbn 14y agoSo that every time some reads the code they have to repeat the thinking from scratch? Even better: after writing then program, run it and save the output and throw away the source code, yeah?
- sethetter 14y agoI feel like I'm seeing a lot of discussion about what should be commented. Just like with tests, this can be hard to put your finger on. Even more so, the level of detail a comment needs to have for it to be useful/useless will vary for each developer reading/working on the code. In my opinion it's better to be overly helpful than it is to leave it all difficult to understand. Also, it's obvious that outdated comments are terrible. It is my expectation that if comments are going to be in the code at all, they should be maintained just like the rest of the code.