'Passing instance variables to instance methods vs. directly accessing them?
Imagine I have a class with an instance member
String instanceMember;
Further I have like 4 instance methods accessing this member. Now I am wondering if there is any real pro/con for either directly accessing the instance member from the instance methods or to pass the instance member as a parameter to each of the instance methods?
Solution 1:[1]
Passing the value as a parameter would imply that you are going to perform the calculation with the parameter value rather than the encapsulated value.
If you are going to operate on encapsulated data then there is no reason to have it as a parameter.
Solution 2:[2]
The reason for having instance variables in the first place is to avoid passing them as parameters: your instance method gets to access them "for free", because they are already in the method's scope.
There are two reasons to pass instance variables to methods, though:
- The method is
static- class methods cannot access instance variables, so you need to pass them explicitly, or pass the object on which to operate - You need to use pass-by-value semantic - in other words, you would like to modify the value passed in, and you would like to avoid creating a local variable. This is often the case when the method is recursive.
If you find yourself writing recursive code that modifies a parameter which started off as an instance variable, in many cases it may be a good idea to make your method private static, and add a public instance method to start the recursive chain and to harvest the results.
Solution 3:[3]
If these methods are public methods that manipulate the state of a persistent member variable, you shouldn't really be passing it around. For example, if you have to do something like the following, it should probably be manipulated directly by the method instead of being passed in:
myObject.SomeMethod(myObject.instanceMember, 15);
This should really just be:
myObject.SomeMethod(15);
If it's something that might change per call (such as, for example, the mysterious 15 in the method above), you'll want to pass it around.
Solution 4:[4]
It will depend a lot on how you use it. If the usage of you class is infrequent, then there will be no obvious difference.
If you are using the class instance a lot, and by many threads, then in some conditions, passing it as a parameter would work a bit faster.
Usually instance members are accessed directly by class members with exeptions of static functions (due to obvious reasons).
So follow your coding conventions and don't worry. By the time it would really matter you will know the answer by heart.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | digitaljoel |
| Solution 2 | Sergey Kalinichenko |
| Solution 3 | Ant P |
| Solution 4 | Valeri Atamaniouk |
