
1
CMSC 433 – Programming Language
Technologies and Paradigms
Spring 2004
Refactoring
March 4, 2004
Lots of material taken from Fowler, Refactoring:
Improving the Design of Existing Code
2
Evolving Software
• Problem
–The requirements of real software often change in ways
that cannot be handled by the current design
–Moreover, trying to anticipate changes in the initial
implementation can be difficult and costly
•Solution
–Redesign as requirements change
–Refactor code to accommodate new design
3
Example
•(p204) Replace Magic Number with Symbolic
Constant
double potentialEnergy(double m, double h) {
return m * 9.81 * h;
}
• becomes...
static final double G = 9.81;
double potentialEnergy(double m, double h) {
return m * G * h;
}
4
Some Motivations for This Refactoring
•Magic numbers have special values
–But why they have those values is not obvious
–So we’re like to give them a name
•Magic numbers may be used multiple times
–Easy to make errors
•May make a typo when putting in a number
•May need to change a number later (more digits of G)
5
Convential Wisdom: The Design is Fixed
•Software process looks like this:
–Step 1: Design, design, design
–Step 2: Build your system
•Once you’re on step 2, don’t change the design!
–You might break something in the code
–You need to update your design documents
–You need to communicate your new design with
everyone else
6
What if the Design is Broken?
•You’re kind of stuck
–Design changes are very expensive
–When you’re “cleaning up the code,” you’re not adding
features
•Result: An inappropriate design
–Makes code harder to change
–Makes code harder to understand and maintain
–Very expensive in the long run