Move Field

Move a field to the class that uses it most.

“A field is, or will be, used by another class more than the class on which it is defined.”

Data is in the wrong place.

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

When to apply (Smells)

  • Feature Envy: Methods in other classes use this field frequently.

Motivation

  • Same as Move Method: Cohesion.

Mechanics (Steps)

  1. Encapsulate the field (create self-encapsulation) if not already.
  2. Move the field to the target class.
  3. Redirect users of the field to the new location.

Explanation

Problem

A field is used more often by another class than its own.

Solution

Create a new field in the target class and redirect all users.

Pros and Cons

Pros Cons
  • Cohesion
  • Interface changes
  • Code example

    Typescript

    Before

    After

    PHP

    Before

    After