Refactoring Legacy Code 
Pablo Machado 
machadoum@gmail.com
Legacy Code? 
Code written using old technology? 
Code written by somebody who doesn't work 
for the company anymore? 
A code very fragile or complicated?
Legacy Code 
➔ Hard to understand and maintain 
➔ Intimidating to be changed
Legacy Code? 
“To me, legacy code is simply code without tests.” 
Michael Feathers
Legacy Code? 
“If you wrote a new feature today, which took you a lot of mental 
energy and time, and tomorrow you'll be afraid to change it …”
Refactoring?
Why Refactor? 
➔ To understand the code 
➔ To improve the health of code-base 
➔ To be confident 
➔ To optimize for readability
Why Refactor? 
➔ To understand the code 
➔ To improve the health of code-base 
➔ To be confident 
➔ To optimize for readability
The Fear Factor
Unit Test 
Characterization tests
Refactor Dilemma 
When we refactor, we should have tests. 
To test we often have to refactor.
Legacy Code Change 
Identify Change Points 
Identify Test Points 
Break Dependecies 
Write Test 
Refactor
Working Effectively With 
Legacy Code
Working Effectively With 
Legacy Code 
Baby Steps
Working Effectively With 
Legacy Code 
Invest only where necessary
Working Effectively With 
Legacy Code 
Know how to use the tools
Breaking Dependencies
External Dependencies 
Production Code
External Dependencies 
Production Code 
Test Code
External Dependencies 
Production Code 
Test Code
Internal/Hidden 
dependencies 
Production Code Refactor To Test
Production Code Test Code 
Test Code 
Internal/Hidden 
dependencies
Refactor Technique
Sprout Method 
When? 
Add a feature as completely new code in a untestable method. 
How? 
Identify the inputs and outputs of the new method 
Create a call for the new method 
Develop the new method with TDD
Sprout Method 
Advantages 
Test new code 
Separeta new cold from the old 
Disadvantages 
Dont test old code 
Dont make the code better
Wrap Class 
When? 
Add a feature as completely new code in complex class. 
How? 
Create a class and extend the old class 
Override the old method and make a call 
Develop the new method with TDD
Sprout Method 
Advantages 
Test new code 
Separeta new cold from the old 
Disadvantages 
Dont test old code 
Dont make the code better
Referências 
http://refactoring.com/
Refactoring legacy code

Refactoring legacy code