Refactoring Move Field


A field is used more in another class than in its own class.


Create a field in a new class and redirect all users of the old field to it.
Move Field - Before
Move Field - After

Why Refactor

Often fields are moved as part of the Extract Class technique. Deciding which class to leave the field in can be tough. Here is our rule of thumb: put a field in the same place as the methods that use it (or else where most of these methods are).

This rule will help in other cases when a field is simply located in the wrong place.

How to Refactor

  1. If the field is public, refactoring will be much easier if you make the field private and provide public access methods (for this, you can use Encapsulate Field).

  2. Create the same field with access methods in the recipient class.

  3. Decide how you will refer to the recipient class. You may already have a field or method that returns the appropriate object; if not, you will need to write a new method or field to store the object of the recipient class.

  4. Replace all references to the old field with appropriate calls to methods in the recipient class. If the field is not private, take care of this in the superclass and subclasses.

  5. Delete the field in the original class.

Tired of reading?

No wonder, there are 7 hours worth of the text on this website.

Try out something different. We've just launched the interactive learning course on refactoring. It has more content and much more fun than a boring text.

Learn more...

Live Example

First time here? No worries!

Everything is quite simple. This example is like video (but much cooler):

  1. After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
  2. You can fast-forward or return to previous steps by pressing arrow buttons on the left.
  3. Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
  4. To check the code for errors, you can press "Compile and test" button ()