Refactoring
Refactoring
Design Entropy
Design
increase over time.
○ entropy (noun): a process of degradation or running
down to a trend to disorder. Design
○ also: chaos, disorganization, randomness.
● As the code is modified (e.g. to add new features, Design
Time
Refactoring
● A refactoring activity can remove some of that design randomness.
Option 2: Refactor the existing code
to a design into which the new
Decision Point feature will integrate more smoothly.
“The danger occurs when the debt is not repaid. Every minute
spent on not-quite-right code counts as interest on that debt.
2
○ A bug in one place is a bug in all of them.
○ Modifications made to one need to be made to the others.
○ Code is longer (this is a smell).
● In this case, the problem can be solved using the
extract method refactor. Some developers practice the rule
of two.
Extract Method: Refactoring Steps
● Create a new method.
● Copy the extracted code into the method.
● Look for local variables on which the extracted code
depends, and add them as parameters to the method.
● Replace the original code with a call to the method.
○ Be sure to pass in the required local variables as parameters.
}
Extract Method: Refactoring Steps
public class MyClass {
Identify duplicate code that exists
// somewhere in the code... in more than one place (usually 3,
for(String name:listOfNames) { but 2 is OK, too).
System.out.println(name);
} (obviously this is an overly simple
example, but you get the idea)
// somewhere else in the code...
for(String name:listOfNames) {
System.out.println(name);
}
}
Extract Method: Refactoring Steps
public class MyClass {
}
Extract Method: Refactoring Steps
public class MyClass {
}
Extract Method: Refactoring Steps
public class MyClass {
}
Extract Method: Refactoring Steps
public class MyClass {
Finally, replace the original code
// somewhere in the code... with a call to the new method.
printNames(listOfNames);