Search code examples
smalltalk

Where are class variables defined in Smalltalk?


I was wondering, if I define a new class variable, for example for the class MyClass, is the definition going to be in MyClass or in MyClass class? Does MyClass class even know about the new class variable?


Solution

  • Yes, class variables are shared with the class and the metaclass. They are also shared with all subclasses (and their metaclasses). A class variable is usually Capitalized, to convey better the idea of being shared in a scope broader than the class. You define class variables in the class (not the metaclass).

    Class variables should not be confused with class instance variables, which are instance variables defined at the metaclass level, i.e., instance variables of the class object. This notion is somewhat obscure despite its simplicity (or because of it): instance variables are always defined in the class to define the shape (slots) of its instances. Thus, if we apply this definition to the metaclass, which is the class of the class, an instance variable defined here defines the shape of its instances, of which there is (usually) only one, the class.

    Going back to class variables, you define them in the class (inst side) and initialize them in the metaclass (i.e., class side). Remember that these are (partial) globals in the sense that will be shared among instances, subinstances, subclasses and metaclasses and so they must be handled with the usual care we treat globals.


    One more clarification

    When we say that instance variables are shared among instances and subinstances, we mean their names (and positions in memory of the object slots); we don't mean their values (contents of said slots). Thus, two instances of the class C will share the name, say color, if the class defines the ivar color, but their values at each of the instances will be independent. In other words, what it is shared is the name, not the value.

    With class variables what is shared is both the name and the value. It is actually the Association object, for example Theme -> aTheme, what's shared. In consequence, any modification to the value of a class variable affects all its references. This is not the case with class instance variables because they are nothing but instance variables, except that they shape the class and its subclasses, rather than regular instances and subinstances.


    For more information on Smalltalk variables see https://stackoverflow.com/a/42460583/4081336