Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Extract Method Tutorial

Introduction to Extract Method

The Extract Method is a refactoring technique used to improve the readability and maintainability of code by creating a new method from an existing block of code. This technique is especially useful when a method is too long or has multiple responsibilities. By breaking down the method into smaller, well-defined methods, developers can enhance code organization and clarity.

When to Use Extract Method

Consider using the Extract Method refactoring when:

  • A method is too long and difficult to understand.
  • The method has multiple responsibilities.
  • You find yourself reusing the same code block in multiple places.
  • You want to improve code readability and maintainability.

How to Perform Extract Method in Eclipse

In Eclipse, performing the Extract Method refactoring is straightforward:

  1. Select the block of code you want to extract.
  2. Right-click on the selected code.
  3. Navigate to Refactor > Extract Method.
  4. In the dialog that appears, enter a name for the new method.
  5. Click OK to complete the refactoring.

Example of Extract Method

Let’s consider an example where we have a method that calculates the total price of items in a shopping cart:

public void calculateTotal(List items) {
    double total = 0;
    for (Item item : items) {
        total += item.getPrice();
    }
    System.out.println("Total: " + total);
}
                

This method can be improved using the Extract Method technique. We can extract the price calculation into a separate method:

public void calculateTotal(List items) {
    double total = calculateTotalPrice(items);
    System.out.println("Total: " + total);
}

private double calculateTotalPrice(List items) {
    double total = 0;
    for (Item item : items) {
        total += item.getPrice();
    }
    return total;
}
                

In this refactoring, we have made the calculateTotal method cleaner and more focused by delegating the price calculation to the new calculateTotalPrice method.

Benefits of Extract Method

The Extract Method refactoring offers several benefits:

  • Improved Readability: Smaller methods are easier to understand.
  • Better Maintainability: Changes can be made in isolated methods without affecting the entire codebase.
  • Reusability: Extracted methods can be reused in other parts of the code.
  • Enhanced Testing: Smaller methods are easier to test independently.

Conclusion

The Extract Method technique is a powerful tool in a developer’s arsenal for writing cleaner, more maintainable code. By following the guidelines provided in this tutorial, you can effectively implement this refactoring technique in your own projects using Eclipse.