Why do programmers ask themselves, “What the F*** was I thinking”, when they view uncommented code that they had written themselves? Can programmers simply reread the code again and try to understand the procedure from the very beginning? Are there any programmers who can program smoothly and not use a single comment?
Re-reading uncommented code can be seriously time-consuming. You might have put hours into the chain of logic driving your program and you probably won’t remember that weeks or years later. Recreating that chain of logic might take as much work as putting it together in the first place. This is especially crucial when a change here can cause a problem over there.
Here’s one simple example I can think of. Let’s say the program is going to show feedback about saving a file. The state is recorded as either 1, 2 or 3 in the software. Just looking at the code will tell you that you’re looking for one of those three numbers; but only your comments are going to tell you things like “Status 1 means data was successfully stored. Status 2 means we’re still working to finish storing data. Status 3 means we’ve given up and are going to produce an error.” That note takes only moments to read; tracing the code that returns each status could take hours.
I encourage my programmers not to write too many comments - I prefer them to concentrate on writing code that’s easy to read without them. Comments that explain how code works are redundant - the code should be readable enough that it explains itself. Comments are needed to explain why the code is written that way, or why it wasn’t done some other seemingly more obvious way.
There are always exceptions of course, some things are just plain complicated and need more comments. And there are different schools of thought. To some extent it depends on the language, and on the development process (test-driven development uses unit tests as a form of documentation, for example).
If I was reviewing that code, I’d send it back. The status codes should use constants with meaningful names: STATUS_WRITE_SUCCESS, or something like that.
Reading the code will only tell you what it does.
The comments can tell you why it does it.
Programs are usually written by applying a set of patterns (*), a “style” if you will. The patterns vary by language and by platform (a C++ program for Windows will look a bit different from a C++ program for Linux, and an Objective-C program for the Mac will be pretty different from both). Of course, there are also stylistic differences between workplaces, etc., some formally regulated, others informal or cultural.
People who are used to working with a given language and platform at a given company learn to recognise those patterns, so that most of the code is pretty straightforward.
The parts that really need documenting (comments and/or formal documents) are the “clever bits”, the tweaks done to optimise performance or to get around a limitation of the language/platform. Basically, the parts that a competent colleague wouldn’t understand easily. As tellyworth was saying, properly chosen class / function / variable names can often serve as documentation.
- The expression “Software Patterns” designates a slightly different, more formal concept.
Yep. Magic numbers are bad. Seeing 60 in the code could mean minutes per hour or seconds per minute, but having a named constant makes it easy for someone reading the code to understand what units are involved in an expression.
Writing useful commentary is both an art and a science. I once got after a co-programmer who didn’t comment much, and he began to write like this:
MOV A,B ;Move the contents of B into register A
STOR B,7 ;Put 7 into register B
…which was not at all what I meant. Instead, look at this:
MOV A,B ;Store the cumulative invoice total in A
STOR B,7 ;Put the number of days in the week in Reg B
Doesn’t that make a difference? The code is the same, but the comments explain what is going on and make it possible to modify it later, long after everyone has forgotten what registers A and B are used for.
This could be one of the best and stupidest ideas I’ve ever heard depending on how it’s implemented. Yes, structures should be simple and obvious, and the comments reserved for the why. But I don’t think I’ve ever encountered too many comments, and encouraging programmers not to write too many comments sounds like a way for some of them to not write any at all.
I find explanatory comments that precede the code to be the most valuable. Defining input and output and the basic function of a simple black box section of code. When well defined in this way, any piece of code can be re-written faster than an obscure problem can be uncovered and fixed. Line by line comments should define any new variable created (except for simple counters and very temp stuff, which should be identifiable by the names used). Each sub-structure should have it’s function identified, and any complex conditional expression should be clarified.
But good structured coding is invaluable. If you can’t follow the execution path of the code without comments, the comments probably won’t help much.
Also, having named constants such as PI are a security against the day the value of PI changes.
(JSB RIP)
I agree on the idea that good code should need minimal comments, provided you use constants instead of values, properly break down sub routines, and use meaningful names for your variables.
Where I find the biggest problem is with things that getinto complex math or computation. Yeah, I can name my function meaningfully and my variables, but particularly when I’m building or going through data structures, or going through database results, it’s not uncommon that I run into special cases that require logic that isn’t obvious, especially if you’re not thinking about that particular special case when looking at it weeks or months later.
I remember one recently where I was testing for something that I thought would always be true, so I thought I could improve the code by removing it, and it broke stuff. Turns out that I had forgotten I put it in there because the query also hit a whole bunch of garbage data that no one uses but I can’t get removed from the database (long story), and I just wasn’t thinking about it because, well, no one uses it. If I’d commented it, I wouldn’t have wasted that time trying to figure it out.
I’ve also done a lot of mathematical programming, and it saves TONS of time there when you need to implement a complex formula. If all you see is a bunch of seemingly random math, especially since it’s not in the same sort of notation you’d tend to see it in, it can very quickly get next to impossible to figure out what’s going on and figure out where the problem is. For that very reason, I always make sure that any complex math gets well commented because of the headaches I’ve had in the past spending hours trying to trace through that kind of stuff.
Over-commenting can be pretty useless. Especially when code changes and the comments don’t. I’ve worked on lots of stuff that had things like this:
i += 2; // add 1 to i
So have I. But the superfluous nature did no harm, it was the inaccurate content that was problematic. Changing code without changing comments is bad, but not an excuse for not commenting.
Developer here. What you are supposed to do is more like this:
i += 2; // We bump the size because we need to have two slots available for the checksum record and the end of file marker record.
But in reality, you’d consider a constant.
That is, you are explaining WHY you find it necessary to bump i up by 2. E.g. if you don’t explain it, someone’s going to come along 6 months later and say, “Why did friedo add this line here? Was he smoking crack?”
Also, outside of an iterative loop (and even sometimes inside one), you’d never call a variable “i” to begin with - you’d document it’s meaning by calling it by a semantically helpful name, like recordIndex, currentTopic, newEmployee, or winningEntrant. A utility method might take a parameter called person or file.
It’s not the volume of comments that’s the problem (though I’m sure you’ve seen those ridiculous classes where every 3-line accessor has a ghastly 30-line comment box copied from a template). It’s that some programmers use comments as a crutch. They figure it’s ok to write unreadable code as long as they add comments - the more the better, even if they don’t actually help (I suspect this comes from the old habit of padding essays as a student to try to meet the minimum word count). Some lazy reviewers do a similar thing: “go back and add comment”, rather than suggesting improvements to the code itself.
Also, the more comments there are, the more likely they’ll go stale - the code gets changed but the old comments stay. You wind up having to read both the comments and the code.
I sort of agree and disagree here. Function and parameter names should be chosen so as to be self explanatory. When they’re not, when the concepts are too complicated for that to be sensible, or when there are caveats or restrictions that need to be pointed out, then yes, an explanation that precedes the code is best. (In the refactored example in that CodingHorror link above, I’d include a comment to point out that it’s a Newton-Raphson approximation).
Inline comments? Occasionally, sure, where they’re needed. But comments shouldn’t define variables. Variable names and types should define the variables.
100% agree.
I’m not saying this is the One True Way, or that it works everywhere. It’ll depend on the development process, team structure, language and so on. Whatever you do needs to fit with the style and conventions of the codebase you’re working on. But I know which codebase I’d rather deal with.
The point was that the comment is both wrong (1 != 2) and useless (the increment had a perfectly obvious purpose in context.)
If there had been no comment on that line, it would never have become a wrong comment in the first place.
Don’t get me wrong; I’m not against comments at all. But there is a right way and wrong way to use them. If you find yourself writing long, involved comments, it might be because your code is hard to understand without them, in which case you should think about making your code better. There are really very few situations where code should be difficult to read.
and, of course
try {
foobar();
} catch (Exception e) {
//0033@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@00ff@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@33ffff77@@@@@@@@@@@@@@@@@@@@@@33ff0000@@@@@@@@@@
//@@@@33ffffff@@@@@@@@@@@@@@@@ffffffff00@@@@@@@@@@@@
//@@@@@@@@ffffffffffffffffKKffffffff33@@@@@@@@ff@@@@
//@@@@@@@@@@ffffffffffffffffaa00@@@@@@@@@@CCffff00@@
//@@@@@@@@@@ffffffffffffffffffBB@@@@@@LLffffffffff@@
//@@@@@@@@@@fQQfffffffffQQffffff@@@@ffffffffffffff00
//@@@@@@@@00fQQfffffffffQQffffff@@@@ffffffffffWWYY00
//@@@@@@@@QQffffffrfffffffQQ44ff@@@@00aaYYXX00@@@@@@
//@@@@@@@@00ffffffffffffPPQQ00ff@@@@@@ffXX@@@@@@@@@@
//@@@@@@@@@@ccffff~~ffffffffffff@@@@@@@@WW@@@@@@@@@@
//@@@@@@@@@@ffPPffffffffffffffff33@@ffYYXX@@@@@@@@@@
//@@@@@@@@@@ffffffffffffffffff00LL@@33TT@@@@@@@@@@@@
//@@@@@@@@@@ffffffffffffffffffffff@@33DD@@@@@@@@@@@@
//@@@@@@@@@@ffffffffffffffff00ffff@@88@@@@@@@@@@@@@@
//@@@@@@@@@@00ffffffffffff00ffff6633DD@@@@@@@@@@@@@@
//@@@@@@@@@@ffffffffffffffffffffffee@@@@@@@@@@@@@@@@
//@@@@@@@@@@ffffffffffffffffffffff@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@YYZZYYXXXXZZffffffffSS@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@66YY0033@@33XXXXYY00@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@00@@@@@@@@@@@@00SS@@@@@@@@@@@@@@@@@@@@@@
//
// GOTTA CATCH EM ALL
}
from
Superfluous comments are not harmless. If the code is full of comments like “increment the counter by 1”, even if they’re all accurate, then the important comments don’t stand out. You have to read everything to see if it’s important (and of course don’t).
On the other hand, if the superfluous comments are left out, then that one comment that says “increment by 2 instead of 1 to fix bug #345” is easily noticed.
Whenever there’s a discussion about comments you’ll always get people saying how commenting can get out of hand with people writing comments like “increment i by 1”.
But…I’ve never seen this. And I’ve seen some horrific code. Shit balanced on top of shit to make a turd jenga.
Classics like code indented so much it went off the side of my display.
But while I’ve seen redundancy in comment templates, I’ve never seen it within a function/method.
A dearth of comments I see all the time however. So I don’t hesitate to tell people to comment as much as they can.
I’ll second this. I mean the only time I’ve really seen a comment like “increment i by 1” it was being done by coders who barely commented anything and wrote extremely ugly code. (I’m convinced in that case the person put the comments in because they were A:Forced and B:To prove comments are worthless. Instead all they proved to me is that they didn’t know how to code.)
Generally speaking I have a similar opinion to the rest of you here. Tell me why you did something a certain way and not another. Also I like to write a good set of comments at the top of a function. (To give me some insight as to what the problem the function was trying to solve, what the return values are. Basically what you’d need to know if you couldn’t get the code.) Oh also I like to write comments to give me the gist of what a block of code is trying to do.
Then again my coding style kind of forces me to write comments. (Since basically I write up a dummy function. They I write a bunch of comments describing in general the tasks I need to do to actually implement that function. Then I actually write up the code.) Like I’ve said, I’ve seen some really ugly code. (I mean I’ve literally seen people repeat the same 8-10 lines of code 70 times instead of writing a flying spaghetti monster damned function. Yes really.)