Commenting out code is evil

Caleb Brown

If you are a software developer you probably use some kind of version control system like subversion, git, or maybe Bazaar, everyday at work. And if you aren't you should be.

When using version control there are some bad habits that need to be broken to get the most from it. One bad habit that really needs to be broken is the habit of commenting out dead code instead of deleting it. It always starts the same way. You have to modify an existing piece of code, so you quickly comment out the old code and start adding your new code. Having the old code is handy - it gives you a reference for the new code you're writing and if something goes wrong you just uncomment it and you're back where you started. Easy.

Once you've finished writing your new procedure you give it a rough test and decide it's good to go, so you commit it to version control. But you leave the original code in - commented out of course, just in case you need it again later.

But not deleting dead code is totally counter-productive in a version controlled world. Firstly because your version control system already stores every past version. And secondly you are making it very hard to identify what's changed between versions when using a diff tool when you just use comments.

For example, here is a diff with a function commented out: --- example1.c 2008-05-28 09:45:22.000000000 +1000 +++ example2.c 2008-05-28 09:45:24.000000000 +1000 @@ -6,6 +6,7 @@ return result; } +/* int some_function_call(int input) { int var = 0; int result = 0; @@ -14,6 +15,7 @@ return result; } +*/ int main(int argc, char * argv[]) { int show_result = 0;

Notice that the only changes you can see are the start and end of the comment block. But what have we removed? Is it just the one function or a couple? Without more context we cannot tell.

Here's an example of the code being deleted instead of commented: --- example1.c 2008-05-28 09:45:22.000000000 +1000 +++ example3.c 2008-05-28 09:28:25.000000000 +1000 @@ -6,15 +6,6 @@ return result; } -int some_function_call(int input) { - int var = 0; - int result = 0; - - // Meaningful calculations - - return result; -} - int main(int argc, char * argv[]) { int show_result = 0;

See how much clearer it is. We can easily tell that the function 'some_function_call' has been removed and nothing else. Deleting the code makes the change show up clearly in a diff.

In the long run this actually makes merging and reverting changes far easier. It helps team members and makes your code that little bit cleaner. Sure it might mean you actually have to learn the more advanced features of your version control system, but it will eventually save you time and help you avoid making mistakes.

Show Comments

Market Place