Code Refactoring
Code Refactoring
Process (OE3C41)
Code Refactoring
• Refactoring does not fix bugs, but it may help find bugs
by scrutinizing code. It may also reduce the further
introduction of bugs by cleaning-up code.
Reading lastReading() {
return (Reading) readings.lastElement();
}
Refactoring: examples
• Consolidate Conditional Expression: You have a
sequence of conditional tests with the same result.
Refactor by combining them into a single conditional
expression and extract it.
double disabilityAmount() {
if (_seniority < 2) return 0;
if (_monthsDisabled > 12) return 0;
if (_isPartTime) return 0;
// compute the disability amount
double disabilityAmount() {
if (isNotEligibleForDisability()) return 0;
// compute the disability amount
Refactoring: examples
• Consolidate Duplicate Conditional Fragments:
The same fragment of code is in all branches of a
conditional expression. Refactor by moving it outside
of the expression.
if (isSpecialDeal()) {
total = price * 0.95;
send();
} else {
total = price * 0.98;
send();
}
if (isSpecialDeal())
total = price * 0.95;
else
total = price * 0.98;
send();
Refactoring: examples
• Rename Method: The name of a method does not
reveal its purpose. Refactor it by changing the name
of the method.
int getInvCdtLmt(){
…
}
int getInvoiceableCreditLimit(){
…
}
Refactoring: examples
• Pull Up Field: Two subclasses have the same field.
Refactor it by moving the field to the superclass.
Refactoring: examples
• Push Down Method: Behavior on a superclass is
relevant only for some of its subclasses. Refactor it
by moving it to those subclasses.
Refactoring: practice
• Some refactorings are controversial.
• Some refactorings are arguably not improving code
quality.
• Some refactorings can in fact be counter-productive
when applied blindly, especially in iterative
development, where design is evolving.
• Have your team adopt a set of refactorings to be
applied, and make sure that refactorings are applied
in a productive manner.
• Apply in combination with the application of design
patterns.
• Use refactoring tools to automate changes, e.g.
Eclipse refactoring, and JUnit testing framework.
References
• Source Making. Refactoring.
http://sourcemaking.com/refactoring
• Martin Fowler, Kent Beck, John Brant, William Opdyke, Don
Roberts. Refactoring: Improving the Design of Existing Code.
Addison-Wesley Professional, 1999. ISBN-13: 978-0201485677.
• Martin Fowler. Refactoring.com.