Sep 25

legacy code black boxingToday, I received a mail referencing this post from Llewellyn Faco.

My first though is: “does adding unit test on legacy code makes sense?”. I beleive it does not. You would like to refactore your code and be sure not to break any feature? Refactoring makes sense only to make your code evolve to change design or add feature and so on. Legacy code that support features you are not aware of (no unit test) … does not need to evolve…does need only to be replaced by other code (with test around this time). So I found this simply useless. 

The second issue I see is the feasibility of the solution proposed by Llewellyn. One nice side effect of unit testing is the decoupling. And usually, legacy code without tests around has a lot of coupling between classes, thrid parties and databases. Even if the legacy code was well written, you always have a damned coupling somewhere deep inside. So there is no way to instanciate the class you would like only for test purpose.

To summarize: you have some legacy code which works (new code has 99% of the bugs) but you don’t know what it does exactly. Why would you like to add test around? I usually add test to describe what I want tmy code to do and reuse these test to ensure evolution (refactoring, redesign…etc). In the case of legacy code: isolate it as much as possible, consider it as a black box and the only possible evolution is replacement!