Docsity

Refactoring: Extract Method and Related Techniques, Study notes of Computer Science

Toggle sidebar
bg1
U
UNIVERSITY OF
NIVERSITY OF M
MASSACHUSETTS
ASSACHUSETTS, A
, AMHERST
MHERST •
•
Department of Computer Science
Department of Computer Science
16 - Refactoring
(with thanks to Frank Tip)
CMPSCI 220 (291A)
Programming Methodology
Fall 2008
U
UNIVERSITY OF
NIVERSITY OF M
MASSACHUSETTS
ASSACHUSETTS, A
, AMHERST
MHERST •
•
Department of Computer Science
Department of Computer Science 2
Refactoring:
Extract Method
!Refactoring for extracting a code fragment
into a method
!Goals:
!Enable reuse
!Avoid cut-and-paste programming
!Make longer methods shorter and more
readable
U
UNIVERSITY OF
NIVERSITY OF M
MASSACHUSETTS
ASSACHUSETTS, A
, AMHERST
MHERST •
•
Department of Computer Science
Department of Computer Science 3
Extract Method: How?
!Create a new method; invent a name for it
!Pick a name describing what the method does
!Copy extracted code from source method to
new target method
U
UNIVERSITY OF
NIVERSITY OF M
MASSACHUSETTS
ASSACHUSETTS, A
, AMHERST
MHERST •
•
Department of Computer Science
Department of Computer Science 4
Extract Method: How?
!Scan extracted code for variables local in
scope to source method
!Only used in target method: declare in target
method
!Used in source method and read but not
assigned in target method: pass in as parameters
!Used in source method and assigned in target
method and new value used in source method:
pass in as parameters and return changed value
!At most one variable can be modified
U
UNIVERSITY OF
NIVERSITY OF M
MASSACHUSETTS
ASSACHUSETTS, A
, AMHERST
MHERST •
•
Department of Computer Science
Department of Computer Science 5
Example: Extract Method
void printOwing(){
Enumeration e = _orders.elements();
double outstanding = 0.0;
// print banner
System.out.println("*************************");
System.out.println("***** Customer Owes *****");
System.out.println("*************************");
// calculate outstanding
while (e.hasMoreElements()){
Order each = (Order)e.nextElement();
outstanding += each.getAmount();
}
// print details
System.out.println("name:" + _name);
System.out.println("amount" + outstanding);
}
U
UNIVERSITY OF
NIVERSITY OF M
MASSACHUSETTS
ASSACHUSETTS, A
, AMHERST
MHERST •
•
Department of Computer Science
Department of Computer Science 6
Example: Extract Method (2)
void printOwing(){
Enumeration e = _orders.elements();
double outstanding = 0.0;
printBanner();
// calculate outstanding
while (e.hasMoreElements()){
Order each = (Order)e.nextElement();
outstanding += each.getAmount();
}
// print details
System.out.println("name:" + _name);
System.out.println("amount" + outstanding);
}
public void printBanner() {
System.out.println("*************************");
System.out.println("***** Customer Owes *****");
System.out.println("*************************");
}
pf3
pf4
pf5

Partial preview of the text

Download Refactoring: Extract Method and Related Techniques and more Study notes Computer Science in PDF only on Docsity!

UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science

16 - Refactoring

(with thanks to Frank Tip)

CMPSCI 220 (291A) Programming Methodology Fall 2008 UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^2 Refactoring: Extract Method

! Refactoring for extracting a code fragment

into a method

! Goals:

! Enable reuse ! Avoid cut-and-paste programming ! Make longer methods shorter and more readable UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 3 Extract Method: How?

! Create a new method; invent a name for it

! Pick a name describing what the method does ! Copy extracted code from source method to new target method UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 4 Extract Method: How?

! Scan extracted code for variables local in

scope to source method

! Only used in target method: declare in target method ! Used in source method and read but not assigned in target method: pass in as parameters ! Used in source method and assigned in target method and new value used in source method: pass in as parameters and return changed value ! At most one variable can be modified Example: Extract Method void printOwing(){ Enumeration e = _orders.elements(); double outstanding = 0.0; // print banner System.out.println("*************************"); System.out.println("***** Customer Owes *****"); System.out.println("*************************"); // calculate outstanding while (e.hasMoreElements()){ Order each = (Order)e.nextElement(); outstanding += each.getAmount(); } // print details System.out.println("name:" + _name); System.out.println("amount" + outstanding); } Example: Extract Method (2) void printOwing(){ Enumeration e = _orders.elements(); double outstanding = 0.0;

printBanner();

// calculate outstanding while (e.hasMoreElements()){ Order each = (Order)e.nextElement(); outstanding += each.getAmount(); } // print details System.out.println("name:" + _name); System.out.println("amount" + outstanding); }

public void printBanner() {

System.out.println("*************************"); System.out.println("***** Customer Owes *****"); System.out.println("*************************"); }

UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^7 Example: Extract Method (3) void printOwing(){ Enumeration e = _orders.elements(); double outstanding = 0.0;

printBanner();

// calculate outstanding while (e.hasMoreElements()){ Order each = (Order)e.nextElement(); outstanding += each.getAmount(); } printDetails(outstanding);

public void printDetails(double outstanding) { System.out.println("name:" + _name); System.out.println("amount" + outstanding); } public void printBanner() {... } UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^8 Example: Extract Method (4) void printOwing(){ Enumeration e = _orders.elements(); double outstanding = 0.0;

printBanner();

outstanding = getOutstanding(e, outstanding); printDetails(outstanding); } public double getOutstanding(Enumeration e, double outstanding) { while (e.hasMoreElements()){ Order each = (Order)e.nextElement(); outstanding += each.getAmount(); } return outstanding;

public void printDetails(double outstanding) {... } public void printBanner() {... } UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 9 Example: Extract Method (5) void printOwing(){

printBanner();

double outstanding = getOutstanding(); printDetails(outstanding); } public double getOutstanding() { Enumeration e = _orders.elements(); double outstanding = 0.0; while (e.hasMoreElements()){ Order each = (Order)e.nextElement(); outstanding += each.getAmount(); } return outstanding;

public public voidvoid printDetailsprintBanner()(double {.. outstanding). } {... } UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 10 Example: Extract Method (6) void printOwing(){

printBanner();

double outstanding = getOutstanding(); printDetails(outstanding); } public double getOutstanding() { Enumeration e = _orders.elements(); double result = 0.0; while (e.hasMoreElements()){ Order each = (Order)e.nextElement(); result += each.getAmount(); } return result;

public public voidvoid printDetailsprintBanner()(double {.. outstanding). } {... } Variant -- Computed Previous Value void printOwing(double previousAmount) { Enumeration e = _orders.elements(); double outstanding = previousAmount * 1.2;

printBanner();

// calculate outstanding while (e.hasMoreElements()){ Order each = (Order)e.nextElement(); outstanding += each.getAmount(); } printDetails(outstanding); } public void printDetails(double outstanding) {... } public void printBanner() {... } Variant Refactored void printOwing(double previousAmount) { double outstanding = previousAmount * 1.2;

printBanner();

outstanding = getOutstanding(outstanding); printDetails(outstanding); } public double getOutstanding(double initialValue) { Enumeration e = _orders.elements(); double result = initialValue; while (e.hasMoreElements()){ Order each = (Order)e.nextElement(); result += each.getAmount(); } return result;

public void printDetails(double outstanding) {... } public void printBanner() {... }

UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^19 Example: Replace Temp with Query (2) double getPrice() { int basePrice = basePrice(); double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else return^ discountFactor basePrice *= discountFactor0.98; ; } public int basePrice() { return _quantity * _itemPrice; } UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^20 Example: Replace Temp with Query (3) double getPrice() { double discountFactor; if (basePrice() > 1000) discountFactor = 0.95; else discountFactor = 0.98; }^ return^ basePrice()^ *^ discountFactor; public int basePrice() { return _quantity * _itemPrice; } UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 21 Example: Replace Temp with Query (4) double getPrice() { return basePrice() * discountFactor(); } public double discountFactor() { double if (basePrice discountFactor() > 1000); discountFactor = 0.95; else discountFactor = 0.98; return discountFactor; } public int basePrice() { return _quantity * _itemPrice; } UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 22 Example: Replace Temp with Query (5) double getPrice() { return basePrice() * discountFactor(); } public double discountFactor() { }^ return^ (basePrice()^ >^ 1000)^?^ 0.95^ :^ 0.98; public int basePrice() { return _quantity * _itemPrice; } Refactoring: Replace Method with Method Object

! Long method that uses local variables in a

way that precludes using Extract Method

! Turn the method into its own object so that:

! Local variables become fields ! Method can then be decomposed into other methods on the same object Replace Method with Method Object: How?

! Create new class, named after method, containing

! final field for object that hosted original method ! Field for each temp variable and parameter in method ! Constructor taking source object and each parameter and initializing corresponding fields ! New method called compute() with same return type as original method

! Copy body of original method into compute()

! Use source object field for any invocations of methods in original object

UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^25 Example: Replace Method with Method Object public class Account { int gamma(int inputVal, int quantity, int yearToDate) { int importantValue1 = (inputVal * quantity) + delta(); int importantValue2 = (inputVal * yearToDate) + 100; if ((yearToDate - importantValue1) > 100) importantValue2 -= 20; int importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; } } UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^26 Example: Replace Method with Method Object (2) class Gamma { private final Account _account; private int inputVal; private int quantity; private int yearToDate; private int importantValue1; private int importantValue2; private int importantValue3; } UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 27 Example: Replace Method with Method Object (3) class Gamma { public Gamma(Account source, int inputValArg, int quantityArg, yearToDateArg) { _account = source; inputVal = inputValArg; quantity = quantityArg; yearToDate = yearToDateArg; } public int compute() {... } private final Account _account; private int inputVal; private int quantity; private int yearToDate; private private intint importantValue1;importantValue2; private int importantValue3; } UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 28 Example: Replace Method with Method Object (4) public class Account { int gamma(int inputVal, int quantity, int yearToDate) { return new Gamma(this, inputVal, quantity, yearToDate).compute(); } } class Gamma { public Gamma(Account source, int inputValArg, int quantityArg, yearToDateArg) {... } public int compute() { importantValue1 = (inputVal * quantity) + _account.delta(); importantValue2 = (inputVal * yearToDate) + 100; if ((yearToDate - importantValue1) > 100) importantValue3^ importantValue2 = importantValue2^ -=^ 20; * 7; return importantValue3 - 2 * importantValue1; } } Refactoring: Move Method

! Method is using or is used by more features

of another class than of its defining class

! Create a new method with similar body in the

class it uses (or is used by) most

! Turn the old method into a simple delegation ! Or remove it altogether Move Method: How?

! Examine features used by source method that

are defined on source class

! Consider whether they should also be moved

! Check for overriding definitions in subclasses

or superclasses

! In general, cannot move if there is polymorphism

UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^37 Move Method: Related Refactorings ! Move Field ! Move a field from source class to target class ! Similar issues ! Extract Class ! Break up a single class into two classes ! Create a new class that will contain some of the functionality of the source class ! Create link between source and target class (e.g., in constructor of source class ! Move functionality to target class with repeated applications of Move Method and Move Field