Why do we have the tendency to comment out code instead of just deleting it? The reason is that we don?t want to lose a piece of code that might come in handy in the future. Maybe we think we?re still going to need it because it solves some problem in an elegant way. Or maybe it?s because it helps us when debugging.
It all boils down to fear of losing information. But commented out code will get in the way more than it will help you, and it’s better off being deleted. I?ll expand on why below and provide some possible alternatives.
Why Commented Out Code Is a Problem
1. It Distracts
At the very least, commented out code will distract you and your team members from the actual code. It?s tempting to think our brains can filter out the commented blocks or that just a few lines won?t make our minds wander. But in reality, the commented out code is just an extra hurdle your brain needs to jump when trying to make a mental model of what the code is doing. And that by itself is hard enough, even in very clean codebases.
2. It’s a Source of Code Rot
More often than not, commented out code will start to ?rot.? The longer code stays commented out, the higher the chances it no longer fits when uncommented.
One possibility is that it just doesn?t compile anymore. The codebase will likely have changed, and the live code will have evolved with it. But the commented out code will still be as it was when you put it in comments.
A more dangerous situation could arise if the code does compile but the behavior of any underlying code is altered. The commented out code may make calls to other components whose behavior has changed. This means the commented out code no longer does exactly what it was intended to do. That’s a potentially be a dangerous problem, and it means you’ll be wasting your time trying to find the cause of an obscure bug. In both cases, it?s a risk to the team and the company, and one that could have been avoided.
Finally, the commented out code may have been a good idea at the time, but fast forward several months or years and you can probably come up with a better solution. Languages, frameworks, and techniques evolve, and in time you will have acquired more knowledge, causing you to solve a problem in a different way. Trust your future self to solve the problem that the commented out code solved.
So how can we avoid the problems caused by commented out code without losing our piece of code forever?