Refactoring

Is the most important step during the practice of the test driven development. The test driven development expects three steps:

  • write failing test
  • make test pass
  • refactor

And in this chapter we will talk about the third one: the refactoring.

Without refactoring

Before tell stuffs about benefit of refactoring, I want to start to talk with what happens when coders don't do it. When we write code, sometimes we add duplication of code. When we don't remove duplication, code base degrades. If we leave code complex, code base degrades. And feature after feature, code becomes difficult to read. And when code is hard to read, is also hard do update.

With refactoring

With refactoring we can take care about code complexity. We must remove code duplication. Remove if statements preferring polymorphism instead. Add collaborators and make code more easy to test. Move responsibility in other classes. There are a lot of activities to do during refactoring process.

Another important activity tied with the ubiquitous language. I've seen a lot of codes updated from big developers team. Each developer, without good feedback and code reviews, maybe can introduce synonyms. Another good activity to do during this step is to introduce an ubiquitous language.

Also Design aspect must be keeped in consideration. Sometimes lines of code to make test green are easy. Easy does not always means simple. After the green bar, we should look for design smells. Maybe introducing right pattern. Some private method that make code more readable.

How to?

There are tools to guide coders ini this activities. For example I like to play with scrutinizer. After each commit, it permorme code analysis and give a feedback of your code complexity. It helps to keep code clean, simple, ... help to remove dupliation.

Also experience is a good friend here. There are no dogmatic rules. Just your experience can drive to the right method to do this practice. Automatic tools. Code review. The purpose is only code improvements.

There is a particular constraint doing kata, that helps in this practice. I call this activity "3 versus 1". Each commit necessary to add a new feature, could be followed by three commit of refactoring. I agree with this practice because I like to make test green instead of make good code as soon as possible. New feature create value for business. Unfortunatly clean code does not create value. But clean code helps developer to add feature. Is our responsiblity to improve our skills in refactoring. Repetition of specific refactoring kata is very important challenge.

Working with legacy code

It is very important to start testing from shortest to deepest branch. After coverage have reached the 100% of code it is possibile to start to do refactoring. Start refactoring from deepest to shortest branch.

See Sandro Mancuso's "Testing and Refactoring Legacy Code" vide.

results matching ""

    No results matching ""