Let’s say you got a project that is really poorly written, contains lots of code smells, wtfs, etc. Moreover, its code structure is so complicated that it is extremely hard to add any new functionality to it. On the other hand, the project works as it is supposed to.
You want to refactor the project, perhaps move it to a new framework, how would you approach this problem? Will you try to build a new one from scratch or use some techniques (specify) to convert the working project into a new one?
I would like to clarify the question a little bit as there is a confusion what do I mean when saying “refactoring”.
I’ll give an example about a car, think of it as a software project. Let’s say you have built your own car. Its construction is pretty weird: engine is upside down, thus all the pipes are laid differently, electricity wires are tangled together and nobody has an idea where do they start or end, etc.
However, everything is working fine: you can easily ride it to shop, work, etc. However, its fuel consumption is a bit too high. Also, if you ever wanted to install new headlights to it, it would be a disaster with all the mess in the wires.
You cant afford buying a new one, so you have to refactor the car somehow: change engines position to normal, make the wires tidy, etc. You need to do this, because sooner or later you will need to change engine, headlights, install new stereo etc.. On the other hand, you still need something to drive you to work every morning, so you must make sure that you don’t screw everything up.
Now let’s go back to the project. How would you refactor the project as complicated as the car above, while not disturbing its primary function and purpose.
I would also like to make this a community wiki. Please edit.
So far the main tendencies are:
- Don’t write a new one from scratch
- Unit test the hell out of it, then start refactoring small pieces
- Read Working Effectively with Legacy Code (Robert C Martin)
Links:
Working is the only kind of project you should be refactoring. If you’re fixing bugs, you’re changing the behavior, and refactoring is explicitly about not changing behavior. But working has different definitions. The good one – the useful one for refactoring – is well-unit-tested. If you’ve got good test coverage (automated tests!), you’re ready to refactor. If you don’t…
Read Michael Feathers’ Working Effectively with Legacy Code. Nibble away at the code. Pick a WTF that particularly offends you, and test the hell out of it, with automated unit tests. Then replace the WTF with something reasonable, ensuring that the tests continue to pass. Lather, rinse, repeat.
Refactor the low-hanging fruit.