Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 748
stefan.at.wpf Avatar asked Apr 18 '13 19:04

stefan.at.wpf


2 Answers

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.

like image 73
digitaljoel Avatar answered Nov 14 '22 20:11

digitaljoel


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.

like image 27
Sergey Kalinichenko Avatar answered Nov 14 '22 22:11

Sergey Kalinichenko