I don’t like dead code
I’ve read so much code in the past two weeks that I have enough material for at least two more posts ;-). If anything in code makes me see red, it’s dead code. First, here’s what I mean by dead code. Unused variables, imports and methods, commented-out sections and branches the program can’t reach all count.
You might think dead code doesn’t get in anyone’s way, but it does. Here are some of the downsides.
- It makes code harder to read and, ultimately, harder to maintain. A method with twice as much dead code as live code is difficult to read and hard to search through. That’s before you get to code the program can’t reach because its conditions haven’t held for ages, perhaps because a flag is obsolete or the range of an input value changed.
- It causes confusion. I’ve lost count of the times I’ve gone to fix a defect and found a commented-out section that seems to do something similar. Is it there on purpose? Was the author trying to tell me something? Is there something I ought to watch out for? Unused variables and unused method or constructor arguments are another example. There’s no shortage of clutter that gets in the way of reading the code.
In my experience, the higher the proportion of dead code in a method or class, the bigger the cesspit. A class or method like that has been rewritten at least five times, at least half the company has had a go at it, and it shows. Sometimes commented-out code is a sign of a quick fix. The author didn’t know what to do with it, or didn’t have time to fix it properly, so they rewrote that part and kept the commented-out version just in case.
There’s even a funny story about dead code, or more precisely commented-out code. One programmer supposedly argued that they left it there so people could see how it used to be. That would have made sense if we were still passing source code around on floppy disks and version control systems such as CVS and SVN were in their infancy.
My advice is to leave no dead code behind. Refactor, refactor, and refactor some more. Get rid of anything you don’t need. You can find the history in version control anyway. And honestly, how many times have you brought dead code back to life?
Related articles
Related CZ Podcast episodes
- #261 · Leadership
On leading people and teams. · Czech audio