Tuesday, April 08, 2008

The golden rule of writing comments

This is something I've wanted to say for a while, and I think many (most?) programmers don't realize it:

Never comment out code.

Comments are for natural-language descriptions of code, or pseudocode maybe.

If you comment out some code, then the parser isn't checking the syntax, the compiler isn't checking semantics, and the unit tests are not unit testing it.

So the code may as well not work. Why have non-working code in your program, especially if it's not called anywhere?

But perhaps the code is there so that you can see the what the program used to do. In that case, just fire up your favorite graphical GIT/SVN/P4/whatever frontend and check out an older revision.

7 comments:

Leif K-Brooks said...

I would never commit commented-out code, but I often find it useful to comment out a line or two to test something quickly. Then I'll either uncomment the line or remove it entirely depending on what happens. Do you think that's a bad idea too?

Slava Pestov said...

I don't consider that a bad idea. I"m talking about commented out code that sticks around for months/years and nobody knows what it's for anymore.

Anonymous said...

Well said.

Daniel

Anonymous said...

slava:

"I don't consider that a bad idea. I"m talking about commented out code that sticks around for months/years and nobody knows what it's for anymore.

Well, you should say that instead. There are obviously lots of times you want to comment out code for perfectly legitimate reasons.

ryan said...

I feel this is a bit too idealistic. The graphical tools are not all that accessible in the current state of affairs and other cases which have been mentioned above. I do agree with the general principle of it though.

Mike said...

Very, very good post. I think that commenting out code (for the long term) really amounts to an admission on the part of the developer that they're not sure enough of what their doing that they can be confident they won't need the old code. In my experience, good development requires more rigorous thinking than that.

Also, as you point out, developers using SCC systems, already have access to historical code.

Groby said...

There are a few cases where you'd want to leave that code in.

* It's temporarily disabled, but intended to be brought back. Having deleted code in your history is not going to remind you

* It's there as a warning example. I.e. we tried this, but it doesn't work because... (You can't always get away w/ just describing the algorithm)

The golden rule here is, if you have to do that, also leave a comment WHY you have that code there.

If there's no comment, I habitually delete commented out code. If you can't tell me why it's there, it doesn't belong.