Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance variables vs parameter passing? Is there an argument?

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?

like image 857
Roja Buck Avatar asked Nov 16 '10 10:11

Roja Buck


People also ask

Can you use instance variables as parameters?

You can use the same name for the parameter as for the instance variable. There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter.

Can a parameter be an argument?

Although parameters are also commonly referred to as arguments, arguments are more properly thought of as the actual values or references assigned to the parameter variables when the subroutine is called at runtime.

Do you pass parameters or arguments?

Arguments are passed by value; that is, when a function is called, the parameter receives a copy of the argument's value, not its address. This rule applies to all scalar values, structures, and unions passed as arguments. Modifying a parameter does not modify the corresponding argument passed by the function call.


1 Answers

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

like image 146
Jagmag Avatar answered Sep 22 '22 03:09

Jagmag