Best Practices for Removing Unused Code

The first thing to remember is all your code should be in source control.

With that in mind, of course you want to delete obsolete code rather than just comment it out. Commented code blocks of any length are dangerous, for at least two reasons:

  1. There's a tendency to assume that the comments were maintained with the rest of the code. This isn't true and can lead to problems like bug regressions.
  2. It's easy to miss an uncommented closing curly brace (for example) in the middle of a long block.

The deleted code is still available if you really need it, but it's no longer cluttering up your working copies. If you're really concerned about discoverability for the old code you can leave a comment indicating code was removed and the revision number you need to find it. At one line, that's a lot better than what the actual code block was using. It's also much clearer this code has been allowed to lapse, and for exactly how long.


If you are using a source control system, deleting the code is my preferred option.

It won't get in your way when working with the current code, and you'll always have the code in the repository if you ever need it again.


A piece of code can have two states.
Either it is active, functioning and tested, in which case it should be in the source control
Or it is obsolete in a way that you can't imagine anyone ever wanting to use it anymore, simply because it is obsolete. In this case it should be deleted.

Not erasing code so that "another developer can find it easily" is a perfectly good reason to keep the code active and compiling. Don't worry about the size of your libraries, the linker removes anything that isn't used.

If you're erasing code and want to warn others of the code that was there and for the reason it was deleted so they won't do the same mistake again, a good comment can be put in place.

Tags:

C#