unom
unom

Reputation: 11476

What is the difference between classVariableNames: '' and instanceVariableNames: '' when setting up a Singleton in Pharo Smalltalk?

One is located on the instance side:

Object subclass: #MyClass
    instanceVariableNames: ''
    classVariableNames: ''
    category: 'MyApp'

The other accessible on the class side:

MyClass class
    instanceVariableNames: ''

Upvotes: 1

Views: 742

Answers (2)

Cyril Ferlicot
Cyril Ferlicot

Reputation: 317

When you create a new class (For example a Pen) you create a Class that is an instance of metaclass (this will be Pen class) and you will be able to get Pen instances that are instance of Pen class.

You can have a lot of Pen but you will have only one Pen class.

An instance variable is a variable of one instance. Each instance has it's own variable. Each Pen can have it's own color.

A class variable is a variable of a Class object (Pen class). As you have only one instance of Pen class, this variable will have only one value. If your pen has a class variable #DefaultColor, myPenInstance class defaultColor will return the same for all the Pen instances.

And last, an instance variable of the class side works as an instance variable of the instance side but for a class.

The difference between a class variable and an instance variable in the class side is that the class variable is unique for the class and it's subclasses while an instance variable in the class side will be specific for each of it's subclasses.

If you have a UniqueInstance class variable that stores a Singleton with an accessor in you Pen, Pen uniqueInstance and PenSubclass uniqueInstance will return the unique pen instance.

If you do the same with an instance variable in the class side, Pen uniqueInstance will return the Pen unique instance and PenSubclass uniqueInstance will return the PenSubclass unique instance.

Upvotes: 2

unom
unom

Reputation: 11476

Here goes, I found bits of information here and there.

Managed to find a good explanation here, pasted in a few lines for reference purposes. People should read the entire column. http://esug.org/data/Articles/Columns/EwingPapers/cvars&cinst_vars.pdf

Classes that use class variables can be made more reusable with a few coding conventions. These coding conventions make it easier to create subclasses. Sometimes developers use class variables inappropriately. Inappropriate use of class variables results in classes that are difficult to subclass. Often, the better implementation choice for a particular problem is a class instance variable instead of a class variable.

What are class variables? Classes can have

• class variables, and

• class instances variables.

Class variables are referenced from instance and class methods by referring to the name of the class variable. Any method, either a class method or an instance method can reference a class variable.

Upvotes: 1

Related Questions