What's better? Creating an instance variable or passing a local variable in Ruby?

In general, what is the best practice and pro / against creating an instance variable, which can be accessed from several methods or creating an instance variable, which is simply passed as an argument to these methods. They are functionally equivalent, as methods can still do the work using a variable. Although I could see the benefit if you update the variable and want to return the updated value, in my particular case the variable is never updated, but only read by each method to decide how to work.

Sample code should be clear:

class Test @foo = "something" def self.a if @foo == "something" puts "do #{@foo}" end end a() end 

vs

 class Test foo = "something" def self.a(foo) if foo == "something" puts "do #{foo}" end end a(foo) end 
+4
source share
3 answers

I do not pass an instance variable. They represent state values โ€‹โ€‹for an instance.

Think of them as part of the DNA of this particular object, so they will always be part of what makes the object what it is. If I call the method of this object, he will already know how to access his own DNA and will do it inside, and not through any parameter that is passed.

If I want to apply something foreign to the object, I will have to pass it through the parameters.

+2
source

As you mentioned, this is a non-functional code issue. With that in mind ...

It is difficult to give a final rule about this, since it is completely context-specific. Is the variable set once and is forgotten about it or is it constantly updated? How many methods uses the same variable? How will the code be used?

In my experience, variables that control the behavior of an object, but rarely (if at all) are changed, are set in the initialization method or given to a method that will be cascading behavior. Libraries and leaf methods have a variable passed into it, because someone will probably want to call it in isolation.

I suggest that you start all over again and then refactor if you notice that the same variable is passed throughout the class.

+1
source

If I need an instance level scope variable, I use the instance variable specified in the initialization method.

If I need a variable that is at the method level (that is, a value that is passed from one method to another method), I create a variable at the method level.

So, the answer to your question is: โ€œWhen should my variable be in scopeโ€ and I cannot answer this without seeing all your code and not knowing what you are going to do with it.

If your object behavior should be statically set at the initialization stage, I would use an instance variable.

0
source

All Articles