Master Refactoring: When to Extract, Inline, and Replace Methods
This article explains key refactoring techniques—Extract Method, Inline Method, Inline Temp, Introduce Explaining Variable, Split Temporary Variable, Remove Assignments to Parameters, and Replace Method with Method Object—showing when to apply each, why they improve code clarity, and providing Java code examples for each transformation.
1. Extract Method
Extract Method means moving a cohesive block of code into its own function with a descriptive name, reducing long or confusing functions and increasing reuse.
void printOwing() {
// print banner
System.out.println("*********");
System.out.println("Banner");
System.out.println("*********");
// print details
System.out.println("name: " + _name);
System.out.println("amount " + getOutstanding());
}After extraction:
void printOwing() {
printBanner();
printDetails(getOutstanding());
}
void printBanner() {
System.out.println("*********");
System.out.println("Banner");
System.out.println("*********");
}
void printDetails(double outstanding) {
System.out.println("name: " + _name);
System.out.println("amount " + outstanding);
}Short, well‑named functions are easier to understand, reuse, and maintain.
2. Inline Method
Inline Method replaces a simple function call with the function’s body and then removes the function, eliminating unnecessary indirection.
int getRating() {
return moreThanFiveLateDeliveries() ? 2 : 1;
}
bool moreThanFiveLateDeliveries() {
return _numberOfLateDeliveries > 5;
}After inlining:
int getRating() {
return _numberOfLateDeliveries > 5 ? 2 : 1;
}Use this when the method adds no value beyond its body.
3. Inline Temp
Inline Temp removes a temporary variable that is assigned once and used only in a single expression, replacing its uses with the original expression.
double basePrice = anOrder.BasePrice();
return basePrice > 1000;After inlining: return anOrder.BasePrice() > 1000; This simplifies code and avoids unnecessary locals.
4. Replace Temp with Query
Replace a temporary variable that stores the result of an expression with a dedicated query method, allowing other methods to reuse the logic.
double basePrice = _quantity * _itemPrice;
if (basePrice > 1000) {
return basePrice * 0.95;
} else {
return basePrice * 0.98;
}After replacement:
double basePrice() { return _quantity * _itemPrice; }
if (basePrice() > 1000) {
return basePrice() * 0.95;
} else {
return basePrice() * 0.98;
}5. Introduce Explaining Variable
When an expression is complex, assign it to a well‑named temporary variable to clarify its purpose, especially in conditional statements.
const bool isMacOs = Platform.toUpperCase().indexOf("MAC") > -1;
const bool isIeBrowser = Browser.toUpperCase().indexOf("IE") > -1;
const bool wasInitialized = wasInitialized();
if (isMacOs && isIeBrowser && wasInitialized) {
// do something
}6. Split Temporary Variable
If a temporary variable is assigned multiple times for different purposes, split it into separate variables, each with a single responsibility.
double temp = 2 + (_height + _width);
Console.WriteLine(temp);
temp = _height * _width;
Console.WriteLine(temp);After splitting:
const double perimeter = 2 + (_height + _width);
Console.WriteLine(perimeter);
const double area = _height * _width;
Console.WriteLine(area);7. Remove Assignments to Parameters
Avoid reassigning method parameters; instead, use a new local variable to hold modified values, preserving the original argument’s meaning.
int discount(int inputVal, int quantity, int yearToDate) {
int result = inputVal;
if (inputVal > 50) result -= 2;
return result;
}8. Replace Method with Method Object
When a large method relies heavily on local state, convert it into a class (method object) so that the state becomes fields, allowing the method to be broken into smaller, testable methods.
class Order {
double primaryBasePrice;
double secondaryBasePrice;
double tertiaryBasePrice;
// long computation ...
double price() { /* compute using fields */ }
}9. Substitute Algorithm
If an algorithm becomes hard to understand, replace it with a clearer one; this may involve extracting the algorithm into its own method or using a library implementation.
String foundPerson(String[] people) {
for (int i = 0; i < people.length; i++) {
if (people[i].equals("Don") || people[i].equals("John") || people[i].equals("Kent")) {
return people[i];
}
}
return "";
}Choosing a simpler algorithm or delegating to a library improves maintainability and readability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITFLY8 Architecture Home
ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
