Move Method

Move a method to the class that uses it most.

“A method is, or will be, using or used by more features of another class than the class on which it is defined.” – Martin Fowler

Stop Feature Envy.

graph LR
    A[Class A::Method] -->|Refactoring| B[Class B::Method]

When to apply (Smells)

  • Feature Envy: Method uses data from another class more than its own.
  • Coupling: High coupling between two classes because of this method.

Motivation

  • Cohesion: Keeps behavior close to the data it operates on.
  • Lower Coupling: Reduces dependency between classes.

Mechanics (Steps)

  1. Check if the method uses data that should be private to the current class.
  2. Copy the code to the target class. adjust references (this -> source class).
  3. Turn the original method into a delegator or delete it.

Explanation

Problem

A method in class A accesses data in class B more than in class A.

Solution

Move the method to class B.

Real world analogy

If you are constantly borrowing your neighbor’s lawnmower to mow their lawn, maybe the lawnmower (and the task) belongs to them (or you should move in with/near them).

Pros and Cons

Pros Cons
  • High Cohesion
  • Might need new accessors (getters)
  • Comparison

    • Inverse Refactoring: None specifically, maybe Move Method back.

    Code example

    Typescript

    Before

    After

    PHP

    Before

    After