Some examples for refactoring with Java
Extract Method: This refactoring involves extracting a section of code that performs a specific task into a separate method, which can then be called from the original code. For example, consider the following code that calculates the total cost of an order:
double totalCost = 0;
for (Product p : products) {
totalCost += p.getPrice() * p.getQuantity();
}
We could refactor this code by extracting the calculation of the total cost into a separate method called calculateTotalCost
:
double totalCost = calculateTotalCost(products);
...
private double calculateTotalCost(List<Product> products) {
double totalCost = 0;
for (Product p : products) {
totalCost += p.getPrice() * p.getQuantity();
}
return totalCost;
}
Rename Method: This refactoring involves changing the name of a method to better reflect its purpose or to conform to naming conventions. For example, consider the following method that calculates the tax on an order:
double calcTax(Order o) {
// Calculate tax on order
}
We could refactor this method by renaming it to calculateTaxOnOrder
:
double calculateTaxOnOrder(Order o) {
// Calculate tax on order
}
Inline Method: This refactoring involves replacing a method call with the body of the method itself. This can be useful when a method is very simple and is not used in multiple places. For example, consider the following code that calculates the total cost of an order:
double totalCost = calculateTotalCost(products);
...
private double calculateTotalCost(List<Product> products) {
double totalCost = 0;
for (Product p : products) {
totalCost += p.getPrice() * p.getQuantity();
}
return totalCost;
}
We could refactor this code by inlining the calculateTotalCost
method:
double totalCost = 0;
for (Product p : products) {
totalCost += p.getPrice() * p.getQuantity();
}
Extract Variable: This refactoring involves extracting a section of code that calculates a value into a separate variable, which can then be used in the original code. For example, consider the following code that calculates the total cost of an order:
double totalCost = 0;
for (Product p : products) {
totalCost += p.getPrice() * p.getQuantity();
}
We could refactor this code by extracting the calculation of the total cost into a separate variable called totalCost
:
double totalCost = 0;
for (Product p : products) {
double cost = p.getPrice() * p.getQuantity();
totalCost += cost;
}