Guide to Extract Method Refactoring in TypeScript
The purpose of the extract method refactoring is to turn a section of code into a new method. The method should be given a name that accurately describes the purpose of the extracted section of code. Extracting methods allows the code to be self documenting and also allows the code to be reused elsewhere thereby reducing duplication.
Example
Here is the original code, unmodified.
class ExampleClass {
public originalMethod() {
let tempVar1 = 1.1;
let tempVar2 = 2.2;
let tempVar3 = tempVar1 * tempVar2;
return tempVar3;
}
}
export = ExampleClass;
Step 1: Create a new and appropriately named empty private method. If the method does not reference any instance variables, then make the method static as well. Verify that none of the temporary variables in the extracted code will be used again in the original method.
class ExampleClass {
public originalMethod() {
let tempVar1 = 1.1;
// method extract start
let tempVar2 = 2.2;
let tempVar3 = tempVar1 * tempVar2;
// method extract end
return tempVar3;
}
private extractedMethod() {
// new empty method
}
}
export = ExampleClass;
Step 2: Copy the extracted code from the original method into the new method.
class ExampleClass {
public originalMethod() {
let tempVar1 = 1.1;
// method extract start
let tempVar2 = 2.2;
let tempVar3 = tempVar1 * tempVar2;
// method extract end
return tempVar3;
}
private extractedMethod() {
let tempVar2 = 2.2;
let tempVar3 = tempVar1 * tempVar2;
}
}
export = ExampleClass;
Step 3: Create method parameters for any local variables in the new method that need to be passed in from the original method.
class ExampleClass {
public originalMethod() {
let tempVar1 = 1.1;
// method extract start
let tempVar2 = 2.2;
let tempVar3 = tempVar1 * tempVar2;
// method extract end
return tempVar3;
}
private extractedMethod(tempVar1:number) {
let tempVar2 = 2.2;
let tempVar3 = tempVar1 * tempVar2;
return tempVar3;
}
}
export = ExampleClass;
Step 4: Assign the return value of the method (if it has one). Comment out the extracted code. Re-run your test suite.
class ExampleClass {
public originalMethod() {
let tempVar1 = 1.1;
// method extract start
//let tempVar2 = 2.2;
//let tempVar3 = tempVar1 * tempVar2;
// method extract end
let tempVar3 = this.extractedMethod(tempVar1);
return tempVar3;
}
private extractedMethod(tempVar1:number) {
let tempVar2 = 2.2;
let tempVar3 = tempVar1 * tempVar2;
return tempVar3;
}
}
export = ExampleClass;
Step 5: Deleted the commented code and clean up formatting as needed. Variable and parameter naming can be cleaned up was well. Re-run the test suite again.
class ExampleClass {
public originalMethod() {
let tempVar1 = 1.1;
let tempVar3 = this.extractedMethod(tempVar1);
return tempVar3;
}
private extractedMethod(tempVar1:number) {
let tempVar2 = 2.2;
let tempVar3 = tempVar1 * tempVar2;
return tempVar3;
}
}
export = ExampleClass;