First, let me be clear about what I mean by "Legacy" code. In most shops legacy refers to anything not currently under active development. A program written a month/year ago for which development had
ceased. At least this is the definition that I am dealing with for the purposes of this post.
We all know the feeling, something happens to cause a change to be made in an application or other component that has long been "just working". And now you have to wade in and get that crawly feeling of rummaging around in someone else's code.
The fears are common, and real, if you are unfamiliar with the code you are also unfamiliar with the original developers assumptions, the cross dependencies in the code base, even potentially external dependencies.
So you hesitate at each step, afraid to change anything for fear of introducing a bug, or outright breaking everything. Cause, you know, if you break it, you own it! Now and forever more.
Often the original developers are no longer easily reachable, either because they have been reassigned, moved on, left the building in a straight-jacket. For whatever reason when we as developers are required to delve into a "legacy" system it often brings a high level of tension along with it!
But it is something we all have to deal with from time to time. So how can we approach this task and minimize both the risk and the fear? In a word, TDD.
Test Driven Development is not just for shiny new development, it can be applied retroactively to existing code. And modifying a legacy application is the perfect time to introduce unit tests to an application that did not already have them.
If the code already had unit tests, and they are passing, you are way ahead of the game, but if not, adding them can be your salvation. When I tackle a legacy project, at the very least I try and identify the portion of the code base I am going to be working with. Then I create a unit test module to test the existing code as is (and my assumptions about that code as well), and get them to pass before I change one line of existing code.
With that done, I can begin introducing changes with some degree of confidence that I am not going to *break* anything along the way, at least not without knowing about it. I begin my Red/Green/Refactor process until I have achieved the desired change, and all the tests are still passing.
This concept seems straightforward, at least to me, but for some reason most developers are reluctant to apply TDD concepts to projects that do not already have them. I am not sure why this is the case, but I know when I have done this I tend to sleep a lot better. Plus it adds real value for the next poor sucker that has to maintain this particular piece of legacy!
Cheers,
Robert Porter
Technorati Tags:
TDD ,
Programming ,
Legacy