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?
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.
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:
static
- class methods cannot access instance variables, so you need to pass them explicitly, or pass the object on which to operateIf 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With