The Crystal Programming Language Forum

Instance variables : recommended pratice

Are there any recommendations regarding the use of instance variables vs getter / setter methods inside the class itself, as in the following example?

class MyClass
  getter var

  def initialize(@var : Int32)
  end
  
  def double1
    var * 2
  end
  
  def double2
    @var * 2
  end
end

[Edit] : Replaced class variables with instance variables

It really comes down to what the intended use of the class is, and whether the value should be instance dependent or not. There are valid use cases for each, it’s not really a use x over y type of situation.

In this case, if the goal is to just double a number, a class isn’t really needed in the first place as you could just do my_num * 2. However for demo purposes, i could probably go with like

class MyClass
  def self.double(value : Int32)
    value * 2
  end
end

The reasoning being the class is essentially just being used as a namespace, really a module might be a better option for this case. Also depends on the context of how this class/object is being used.

I think the question was more “when should I use var vs. @var inside a method”.

My answer is: both are the same. Choose whichever you prefer. var is shorter. It also allows being redefined by subclasses but it usually doesn’t matter.

Also performance is exactly the same in both cases.

1 Like

Ah, in that case the title should be updated. Class variables are something different :p

1 Like

I like to use @var because its visually different and instantly obvious where its defined and coming from.

When I use “var” (and especially “var=”) its because it allows you to do things when the variable is accessed. (logging, debugging outpouts, whatever)

3 Likes

@asterite, @Blacksmoke16 : yes, that was the meaning of my question, and, of course, I should have written instance variable, not class variable. Interesting to know performance is the same for either syntax.

@mavu : your answer suits me perfectly.

I would say generally using methods is better. Why care where the thing comes from or what the thing is? Helps with refactoring too.

Hmm, isn’t it some difference, however ?
The following code compiles :

class MyClass
  property var

  def initialize(@var : Int32 = 42)
  end

  def inc
    @var += 1
  end
end

but replacing @var += 1 by var += 1 ends in error:
Error: ‘+=’ before definition of ‘var’

Is this expected behaviour ?

Yes, because var += 1 is expanded to var = var + 1, so an assignment expression. And assignment expressions create local variables, shadowing any method. To disambiguate this you need to do self.var += 1.

2 Likes