Thursday, July 1, 2010

The Refactoring March


I’ve been hired to help refactor code. The lead developer and project owner know they have a code mess and they want it fixed. Rewriting the application is not an option, but the code base is tightly coupled and has turned into a ball of mud. Where does one start?

At first (and still am to a certain degree) perplexed about the process. Core features are intertwined in a whimsical manner where no thought of abstraction or single responsibility has ever taken place. Procedural code runs rampant among threads, inherited classes (abstract or not) and a myriad of if statements. And as developers have tried to “improve” the methodology of making calls into the bowels of the communication layer it has quickly become a congealed mess.

While I have faced similar issues with code in the past, I’ve never been given the green light to really fix the problems and make it work. I’ve argued unsuccessfully to rewrite projects because the code base is so messed up that only a proper burial into the sea of electricity was fitting. This does not sit well with people who have many years of time and money invested into the project(s). It requires more creative thinking to get the code base into a true usable state.

I’ve told the project manager that we need to stop current development. Adding more features will only serve to create more threads of illegitimate code. The second step I’ve taken is getting the source code repository into a better managed state so we know what code is getting developed, tested and in production. I wouldn’t say the previous state of source control was horrible, but it lacked the ability to exist in these different states independent of each other.


Next I traversed through the code and began to pick at the low hanging fruit. Simple things like removing needless comments (almost all of them), unused variables, unused methods and classes, clean up using declarations and other tidying refactors to make the code a bit better to read. In Fowler’s book, “Refactoring: Improving the Design of Existing Code” he indicates that code not placed with unit testing is considered legacy code and thus needs to be refactored. This means the start point for refactoring is getting the code wrapped in unit tests.

This means the developers need to have the ability to write unit tests. This also means we need to have good coding standards and reviews as we move forward. Since the company is hiring real Sr. Developers we have a nice core team that understands these principals. We now need to get the existing team to understand these are not suggestions, but requirements if we are to bring the code base back to life.

My fear is that while we might do a good job of cleaning up the cuts and bruises we will need to use the electric paddles a couple of times in this process to keep the pulse going.