Refactoring Legacy Code
Revision r1.1 - 12 May 2004 - 17:04 GMT - PhlIp"LegacyCode" is code lacking UnitTest?'s that would permit chronic design improvements.
Such code raises serious questions, from "may I refactor my boss's interesting code?", to "how do I keep from adding bugs without tests?"
Robert Atkins wrote, on the XP newsgroup:
I've just started work in a company that is not XP but is "Agile friendly" and I think would like to be more XP as a whole. So for my part I'm trying to not write any code without tests and I've begun to "subtly pair".
There's a lot of code I'd like to refactor. Heaps of duplication across the codebase, some really nasty tight coupling and some just plain poorly written code.
How do I do this so it doesn't look like I'm saying, "I think whoever wrote this is an idiot!". Note that I don't necessarily think that. But coming in off the street and saying, "All this needs changing!" could be seen as confronting.
Never do anything without multiple reasons to do it. R around a bug's site,
to leverage your new awareness of its control flow. R if something really
sucks, and if someone asks a question about it. R to introduce a few learner
tests. R only with a pair. R with the codes author - "I need whoever wrote
this to help on it.."
As code cleans up, add lots of TODO comments, saying where to R more. Fixing
them is totally optional. (Comment things you must clean during this
cycle, such as temporary changes, with "BULL" or similar.)
Then, as the team realizes the TODOs are holding them back, start a new
module. Comment it "TODO-free zone". Use test-first to force all code that
qualifies to migrate in. Slowly, steadily, you can replace cruft with
healthy code, as a side-effect of rapidly producing versions of it with
fewer bugs.
--PhlIp
- Don't refactor without tests. That's not refactoring, that's rewriting. If you need to refactor something that's not under test, put it under test first. (Read Michael Feather's book Working Effectively with Legacy Code)
- Don't refactor just to refactor. Only refactor in the area that you are currently working; and always toward getting new functionality in place.
- Don't refactor alone. Always gets someone else's advice and help.
At the XPAU conference last year we had a on-going lab exercise called
"Fit-Fest". We had a small application working and a group of stories
to be implemented against it. We even had acceptance tests written
for the new stories. Folks would pop into the lab for a couple of
hours to work on the project.
By the end of the conference there were no new stories implemented, no
new acceptance tests passing, and yet the code had grown to three
times it's original size. Folks had been coming into the lab to
refactor as opposed to make new stories work. Be wary of this.
--Robert C. Martin (Uncle Bob) |
|
|