refactoring 101 william c. wake [email protected] 2-2-2000
TRANSCRIPT
Refactoring
Improving the design of
existing code, without changing
its observable behavior.
Agenda
“Code smells” Solid set of unit tests Refactorings Demo Questions/Discussion
Code Smells“If it stinks, change it.”
Duplicate code Switch
statements Long method Large class Data class
(“data bag”)
Long parameter list
Primitive obsession
Temporary field etc.
Unit Tests
Automatic Self-checking Run often (almost constantly) “If you want to refactor, the
essential precondition is having solid tests.” -- M. Fowler
JUnit
Unit testing tool Supports creating and running test
suites Available for Java & several other
languages http://xprogramming.com
Refactorings
Fowler’s book has a catalog There are many more Often reversible Pay attention to the mechanics Let the compiler tell you Small steps with constant tests
Extract Method
BEFOREvoid f() { …. // Compute score score = a * b + c; score -= discount;}
AFTERvoid f() { …. computeScore();}
void computeScore() { score = a * b + c; score -= discount;}
Encapsulate Field
BEFORE
public String name;
AFTERprivate String name;
public String getName() {return name;}
public String setName(String newName) { name = newName;}
Introduce Null Object
BEFORE
if (user == null) plan = Plan.basic();else plan = user.getPlan();
AFTER
Parameterize Method
BEFORE AFTER
WebService WebService
handleGet(…)
handlePut(…)
handle(serviceType,…)
Replace Constructor with Factory Method
BEFOREpublic User(int type) { this.type = type;}
AFTERUser(int type) { this.type = type;}
public static UsercreateUser(int type) { return new User(type);}
Replace String with Stringbuffer
BEFORE
String a, b, c; …return a + b + c;
AFTER
String a, b, c; …Stringbuffer result = new StringBuffer(a);result.append(b);result.append(c);return new String(result);
(Not in Fowler’s catalog)
Demo
Hand out real code seeded with refactoring opportunities
Audience takes 5 minutes to identify smells
Audience helps refactor in IDE Observe the motion back and forth
between test and code
Discussion
Questions?
More Information
Refactoring, by Martin Fowler Extreme Programming Explained,
by Kent Beck Anything by Jon Bentley -
Programming Pearls, More Programming Pearls, Writing Efficient Programs