Friday 17 January 2014

Delete Dead Code

If you are working on a large codebase the chances are there is some dead code in there. Maybe a class that isn’t used any more, an if statement whose condition can never be satisfied, or a click handler for a button that is no longer visible on the GUI. This code could be simply be deleted and it would have no negative effect on your application.

But what harm is it actually doing? Does it even matter if your code is littered with vestigial methods? The impact on build times and memory consumption is probably negligible, so why care about the presence of dead code? Why spend time eliminating it from your codebase?

The reason to remove is simple: dead code wastes time. There are several reasons ways in which this happens. First, unused code can break the build. A change you make in live code can cause a compile error in dead code, forcing you to investigate and fix. Or the unit tests for the dead code start failing and again an investigation is needed. The trouble is, usually it’s not obvious that you’re fixing problems in dead code, so you end up wasting your time fixing it when you could just delete it.

I once worked on a large VS solution where an entire project stopped compiling with an ILMerge error caused by an unrelated feature added elsewhere. It took someone three days to fix. On further investigation, the non-building project was in fact completely obsolete. Had it been deleted at the time it was obsoleted, those three days would have been saved.

Dead code also hinders future development. When you are contemplating making a change to a method, you’ll probably search the codebase for all places that might be affected. So you do a “Find all references”, and discover that there are 12 places this method is called. For each of those 12 places, you’ll need to read the code and understand what it is doing, before you know if your change is safe to make. Each one of those references will take time to understand, and if they seem particularly complex, might even dissuade you from making your desired change. If any of those references came from dead code, then it was a waste of your time even thinking about them.

Perhaps you don’t believe me. Here’s a simple experiment you can do. Next time you come across a class that has been unused for several years, take a look at the source code history. In my experience, an unused class will end up being modified at least once every four months. Which means it is probably being read and thought about every couple of weeks. It’s slowing you down by making you think about it.

In conclusion, if you come across dead code in your codebase, delete it. Make sure you are the last person whose time is wasted by it.

No comments: