Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you look at which variables a method uses before refactoring a large class into smaller ones? [closed]

I am interested in exploring the idea that the relationship between methods and the member varialbes they use can give a hint to how the class could be broken up into smaller pieces. The idea is that a group of variables will be closely related to one responsibility and should be contained in one class according to SRP.

For a trivial example, a class such as:

public class Rectangle {
  private int width; 
  private int height;
  private int red,green,blue;
  public int area() { return width * height; }
//just an example, didn't check the api.
  public Color color () { return new Color (red, green, blue); } 
}

Should be refactored into:

public class Rectangle {
  private Dimension size;
  private Color color;
  ...
}

Because the break down would be:

Area: width, height Color: red, green, blue

Since these variables are used in the same method they are clearly related and could be made into a class of its own. I know this example might be too trivial but bear with me and try and think bigger here. If other methods also use these variables they are most likely also related and could also be moved into the new class.

Just for fun I created a little plugin for Eclipse that tries to do this. It will have a break down on methods->variables, variables->methods and also tries to group methods together after which variables they use either directly or indirectly.

Is this something that you do when coding, and is it actually helpful?

like image 585
willcodejavaforfood Avatar asked Nov 25 '25 06:11

willcodejavaforfood


1 Answers

I can't say that this has ever been something that I've thought about while coding. Yes, it could potentially result in some improvement, but I think what you'd find yourself doing in practice is to create a large number of classes that would be even more awkward to deal with.

There may be some merit to it as a "code smell", though. If you see a class with tons of member variables, and most are only used by a handful of methods, that's generally a bad sign.

like image 57
jsight Avatar answered Nov 26 '25 20:11

jsight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!