Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 740
Shruti Rawat Avatar asked Nov 15 '13 06:11

Shruti Rawat


People also ask

How do you access a method from one class to another?

In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance.

Can you call methods from a different class?

You can also use the instance of the class to call the public methods of other classes from another class. For example, the method FindMax belongs to the NumberManipulator class, and you can call it from another class Test.

How do you move a method to another class in Python?

If you go to each method and right-click on its name, the menu has a "Refactor" option, which leads to a "Move" option.

How do you pass a method to another class in Java?

To call a method in Java from another class is very simple. We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.


1 Answers

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

like image 105
René Link Avatar answered Sep 22 '22 08:09

René Link