Code Cleanup (3 Part Series)
Do you remember cleaning your room as a kid, because your parent made you do it? What did that cleaning session look like? Most likely you would just propel your old shirts into the closet, put your toys in a box along with the shoes and a half – finished bag of candy, and then, to top it off, kick that box under the bed. Your room looked clean.
And that is the only thing you can truthfully say about it. It looked clean.
But it wasn't.
Let's not be kids while cleaning our code. Mindless extracting chunks of code into separate methods is arguably one of the worst things you can do with a piece of foul-looking code.
Face it. You were trying to go easy on yourself. But you did yourself no favours. You've managed to create at least one additional problem to deal with. Now, not only that the code is looking bad, but it is also hiding in the shadows, hoping you won't find it.
I've recently seen a lecture by two gentlemen, on how to approach legacy code. I was blown away by their advice. It was so simple. And even better,they kept presenting it as a minimum effort method. The method was to extract anything and everything we can into methods before you even figure out the semantics behind it.
Their selling point for this approach was: "Let the code tell you what it does".
While I agree with this standpoint, the context of it is extremely important. Bad code does not tell you what it does. Or even worse, it tells you the wrong thing.
I have tried this method in practice and very soon found out how bad it was. The method seemed fine for a while. I was doing the refactoring, moving everything into separate methods. The code looked cleaner and more readable.
Until I took a coffee break and came back to it. It wasn't even remotely more readable. As a matter of fact, I had just hidden the garbage code behind a fancy method name which didn't even properly describe what it was doing. I made it harder to read, since you had to propagate through 5 meaningless method names to find some code that is actually doing something buried in the very core of it.
Lesson of that day : „If something seems too good to be true, it probably is.”
Now when I think about it, it doesn’t even sound that good. To an engineer, how can an idea of doing something mindlessly and without any thought, be entertaining?
There are no shortcuts to high-quality, readable and maintainable code. We can't put dirty socks in a box and call them clean. Do your job. Re-engineer, re-design, figure out a completely new architecture for the entire system.
Sloppy code cleanup is worse than none.