Composing Methods
Much of refactoring is devoted to correctly composing methods. The refactoring techniques in this group streamline methods, remove code duplication, and pave the way for future improvements.
Extract Method
Create a new method and name it in a way that makes its purpose self-evident.
printOwing(): void {
printBanner();
// Print details.
console.log("name: " + name);
console.log("amount: " + getOutstanding());
}printOwing(): void {
printBanner();
printDetails(getOutstanding());
}
printDetails(outstanding: number): void {
console.log("name: " + name);
console.log("amount: " + outstanding);
}Inline Method
When a method body is more obvious than the method itself, use this technique.
Make sure that the method isn’t redefined in subclasses. If the method is redefined, refrain from this technique.
Extract Variable
You have an expression that’s hard to understand.
Condition of the if() operator or a part of the ?: operator in C-based languages
A long arithmetic expression without intermediate results
Long multipart lines
Inline Temp
You have a temporary variable that’s assigned the result of a simple expression and nothing more.
Replace Temp with Query
You place the result of an expression in a local variable for later use in your code.
Substitute Algorithm
So you want to replace an existing algorithm with a new one? Gradual refactoring isn’t the only method for improving a program. Sometimes a method is so cluttered with issues that it’s easier to tear down the method and start fresh.
Split Temporary Variable
You have a local variable that’s used to store various intermediate values inside a method (except for cycle variables).
Each component of the program code should be responsible for one and one thing only, which makes it much easier to maintain the code.
Remove Assignments to Parameters
If a parameter is passed via reference, then after the parameter value is changed inside the method, this value is passed to the argument that requested calling this method.
Multiple assignments of different values to a single parameter make it difficult for you to know what data should be contained in the parameter at any particular point in time.
Replace Method with Method Object
You have a long method in which the local variables are so intertwined that you can’t apply Extract Method. The first step is to isolate the entire method into a separate class and turn its local variables into fields of the class.
Isolating a long method in its own class allows stopping a method from ballooning in size. This also allows splitting it into submethods within the class, without polluting the original class with utility methods.
Last updated