How to move a method from a class to another class when two classes are not at all related

Shruti Rawat picture Shruti Rawat · Nov 15, 2013 · Viewed 15.2k times · Source

I am trying to re factor some code by breaking a class into several other classes. to do so i want to move some methods already existing in my old class to new class. But these methods are being referred in a lot of places and manually updating the references seems tiresome. So is there any way to move methods as well as update their references in eclipse?

Answer

René Link picture René Link · Nov 15, 2013

I would do it this way:

  1. Ensure that your tests work and the code to be re-factored is covered. If you don't have tests write tests. They are your safety rope.
  2. Use the re-factoring pattern extract superclass to create the new class that you want to move some methods to.
  3. Use the re-factoring pattern pull up methods to move the methods along with the variables that they need to the superclass. Now you will see if the methods you want to move and the instance variables have dependencies to the other methods that you don't want to move. If so you must first break this dependencies.
  4. Find all client code that should use the new extracted class instead of the "old" class and rewrite it to the new extracted class.
  5. Remove the "extends" relationship between the two classes. Now the client code should work or you missed something.

Also a good book for learning how to apply re-factoring patterns is Working Effectively with Legacy Code