Move Method | Drawbacks and Resolving Strategy

A method is transferred from one class to another using the refactoring technique known as the “Move Method.” This method is useful when a method appears to be more closely related to another class than it is to its own or when the method uses more features from another class than it does from its own.

Ways to Apply Move Method Refactoring Technique

The Move Method refactoring technique involves the following steps:

  • Determine the direction you wish to go in. Depending on its purpose and the data it uses, think about if it makes more sense for the method to be a member of a different class.
  • Determine the target class to which the method should be transferred. Find a class that already has relevant data or actions that the method you wish to relocate uses.
  • With the same signature as the original method, create a new method in the target class. The relocated method will be used to call this new method.
  • Create a forwarding method that transfers the call from the source class to the target class’s relocated function. This enables the source class’s method to be called by existing code without requiring any changes.
  • Change all references to the original method in other classes to use the target class’s new location for the method.
  • Check the program to make sure the change hasn’t introduced any problems or strange behavior.
Move Method

Problem

A method is utilized more frequently in another class than in the one it belongs to.

Before Refactoring

class Order:
    def __init__(self, items):
        self.items = items
    
    def calculate_total(self):
        total = 0
        for item in self.items:
            total += item.price
        return total
    
    def print_order(self):
        print("Order Details:")
        for item in self.items:
            print(f"- {item.name}: {item.price}")

class Item:
    def __init__(self, name, price):
        self.name = name
        self.price = price

item1 = Item("Item 1", 10)
item2 = Item("Item 2", 20)
item3 = Item("Item 3", 15)

order = Order([item1, item2, item3])
order.print_order()
print("Total:", order.calculate_total())

Solution

The most frequently used method should be moved to a new method that is created in the class. A reference to the new method in the other class should be added to the original method’s code, or the original method itself should be deleted.

After Refactoring

class Order:
    def __init__(self, items):
        self.items = items
    
    def calculate_total(self):
        total = 0
        for item in self.items:
            total += item.price
        return total

class Item:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def print_details(self):
        print(f"- {self.name}: {self.price}")

class Printer:
    def print_order(self, items):
        print("Order Details:")
        for item in items:
            item.print_details()

item1 = Item("Item 1", 10)
item2 = Item("Item 2", 20)
item3 = Item("Item 3", 15)

printer = Printer()
printer.print_order([item1, item2, item3])

order = Order([item1, item2, item3])
print("Total:", order.calculate_total())

The print_order() method was transferred from the Order class to a new Printer class in the refactored version. The Order class is in charge of managing the items and calculating the total, while the Printer class is in charge of printing the order details.

With the help of the Move Method refactoring technique, we have increased the modularity and maintainability of the code by reducing the responsibility of the Order class and improving the separation of concerns.

Drawbacks of the Move Method Refactoring Technique

The Move Method refactoring technique has various disadvantages that should be taken into account, despite the fact that it is frequently advantageous:

  • Added Complexity: Adding more complexity to the code base can result from moving a method from one class to another. Changing references to the moved method and altering existing code that calls the method may be necessary. Because of this intricacy, reworking may take longer and be more error-prone.
  • A method that is moved to a different class may depend on different data or have different dependencies, which could result in
  • Coupling Increased: Moving a method to a different class might enhance the coupling between the source and target classes. The target class may grow more reliant on the source class’s internals, resulting in a more tightly tied codebase. It is critical to ensure that the shift does not introduce undue reliance or contradict principles such as the Single Responsibility Principle.
  • Inconsistent Class Obligations: Refactoring might result in inconsistent class obligations if the moved method is not clearly related to the target class or if the target class already has a different responsibility. Methods may exist in classes where they do not naturally belong, making the code more difficult to comprehend and maintain.
  • breakage. If not handled appropriately, this could potentially damage the transferred method’s functionality or lead to the introduction of new issues. To make sure the behavior is still intact following the refactoring, careful testing is required.

Resolving Strategy

When using the Move Method refactoring technique, it is critical to have a resolution strategy in place to resolve potential issues and minimize the impact on the codebase. Here are some techniques for mitigating the disadvantages:

  • Plan and Test: Before refactoring, carefully plan and test the impact of shifting the method. Determine any potential challenges or dependencies that may occur as a result of the migration. Create a robust testing plan to ensure that the code’s behavior remains unchanged after refactoring.
  • Refactor in Smaller Pieces: Rather than shifting the method all at once, consider splitting it down into smaller pieces. This can aid in managing complexity and minimizing the likelihood of problems being introduced. Move portions of the method gradually and check for correctness at each stage.
  • Introduce Adapters or Interfaces: If the source and target classes have dependencies or coupling issues, try introducing adapters or interfaces to decouple the classes. This can help to reduce increasing coupling and allow flexibility in dealing with class dependencies.
  • Examine Class Responsibilities: Examine the responsibilities of the source and target classes to ensure that the relocated method is adequately aligned with the goal of the target class. Consider reworking the target class or evaluating the move if the move might result in inconsistent or unclear responsibilities.
  • Encapsulation and Information Hiding: Examine the visibility and access modifiers of the moved method and any related data. Ensure that the principles of encapsulation and information hiding are not broken. Consider modifying access levels and introducing getter/setter methods or other forms of limited access if necessary.
  • Restructuring and Iterate: After the initial move, continue to iterate and restructure the code as needed. Refactoring is a continuing process, and it is probable that more changes or modifications will be required to optimize the design and maintainability of the software.

Yocan also views other refactoring techniques:

Leave a Reply

Your email address will not be published. Required fields are marked *