How can we refactor code without unit tests?

When working with legacy code, we want to add unit test for the legacy code, but in the most cases, we find the legacy code is not testable, we need refactor code firstly, but we don’t have any unit tests, how can we refactor code without the protection of unit test? This’s the most questions from developers.

 

Before answer the tough question, let’s firstly review what’s the refactoring?

 

"Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure." – Martin Fowler

 

Martin didn’t say anything about unit test in the definition of refactoring, although we know it’s the perfect way to do the refactoring with the protection of unit test. So as long as we can keep existing code behavior, we still can do refactoring without unit testing.

Normally, we are afraid of code refactoring without unit tests, especially for the code with too many bad smells, why? Because more bad smells there are, more and bigger changing there will be; more and bigger changing we will make, more and bigger risk we will properly bring. We are afraid of risk, that why we don’t think we can do code refactoring without unit tests. But I think risk is NOT the key, the key is how much and how big the risk we will bring? If the risk is small enough, it will not be a problem and we will have much confidence to take it.

 

How can we do? It’s very simple. It’s just “Baby Step”. We split the whole refactoring with many small steps and make only small changing in each step. If the changing in each step is small enough, we could have much confidence to believe what we changed is equivalent transformation and we wouldn’t bring risk during each changing. Eventually, we can finish the whole refactoring without bring any risk.

         Normally, this kind of refactoring method includes many basic refactoring skills and the whole refactoring process is also very coherent; so firstly we need be very familiar with the basic refactoring skills, like extract method, inline code, introduce fields and move code. Secondly, we need ReSharp tool which can effective keep synchronous between what we are doing and what we are thinking.

         According my practices in the real cases, the code will be able to always keep unbroken in the whole refactoring process, sometime, code will probably be broken in a very short time (about 1 or 2 minute), but I can fix it very quickly because I just bring only small changing.

 

  This refactoring method is very useful and powerful, especially for the untestable legacy code. Through two or three practices, we will be able apply it in our daily coding work.

posted on 2012-08-04 10:51  没Ready  阅读(172)  评论(0编辑  收藏  举报

导航