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.
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)
@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.
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.