19

So,

I have been working on re-factoring some legacy code recently and have found myself questioning the validity of some of the re-factoring decisions I have been making. One such query has been about the use of instance variables for object sharing between methods within an object.

Specifically, there are a number of places where constructors & methods have been split up and local variables promoted to instance variables, allowing access from the now separate methods. This, to me, seems wrong. It breaks encapsulation, alters scope and can affect life cycle, however, some of these classes are performance related and thus I wonder what the implication of re-factoring these methods to use parameter passing instead may be?

More to the point I wonder whether my assumptions even hold water? Is parameter passing of objects preferable to instance variables when it comes to sharing between private methods?

Roja Buck
  • 2,354
  • 16
  • 26
  • 1
    A bit old but I think it's a duplicate : https://stackoverflow.com/questions/346169/when-to-use-an-object-instance-variable-versus-passing-an-argument-to-the-method – Igor Beaufils Sep 29 '22 at 14:56

2 Answers2

10

I definitely think that you shouldnt just be taking local variables and making them instance variables just to avoid passing them around. That is definitely not a good idea for reasons that you have already enumerated including the fact that it bloats up the class itself.

Whether what that instance variable represents is a property of that class itself or not is not something that can be generically addressed. It would depend on the entity that the class represents. However, this design is linked to the design of the class itself and maybe its the overall class design that needs to be relooked.

If maybe you provide an example of the refactoring that you are referring to, it might help to provide a better answer in that context

Jagmag
  • 10,283
  • 1
  • 34
  • 58
9

On the plus site this way you wont have to pass those arguments to other methods. When a method has more than three arguments (according to Robert Martin's Clean Code) readability of your code starts to decrease fast. I think you should mix these two methods to bet the best result.

What you could do is look if you can extract a new class from part of the existing one. When just part of the methods use these instance fields, perhaps those methods are doing something that can be abstracted. This way you can create a new class with the instance fields as constructor arguments or properties and instantiate it.

Steven
  • 166,672
  • 24
  • 332
  • 435