• Post Reply Bookmark Topic Watch Topic
  • New Topic

Instance variable vs method argument  RSS feed

 
Vopli Vidoplyasova
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here are two short examples:




In the first one an object reference is passed to another method as an argument, in the second one an instance variable is declared that both methods can access. It works both ways but I'm wondering what the best design decision would be, given the variable represents the inner life cycle of the object and is not going to be accessed from the outside of the class. Is there some rule of thumb for cases like this based on performance or anything else?
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Totally depends on the actual usage.

I find the first easier to test, because I can test the second method in isolation, and its more functional in nature. The second leaves some use cases ambiguous and relies on knowing about the non-local side effects.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you actually need that SomeClass object, or do you only keep a reference to it so it can be used in the second method? If that's the case, don't. You create a potential memory leak, because you keep a reference longer than you need to.
 
Vopli Vidoplyasova
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The sole purpose of having that instance variable is so the second method can access it. In fact, it used to be one huge method and I decided to subdivide it into several smaller ones. The first method passes the SomeClass reference to the second one, second one sets some parameters it and sends it back (you know, instead of having all that code inside the first method).
Anyway, you guys answered my question, thanks a lot!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!