Pattern: Class Initialization


Context

When a New Class is created the class variables or class instance variables defined for it will be nil by default. If there are sensible initial values for these variables, then the new class should be intialized appropriately. Very often, a class variable is used to implement a Singleton, and it is necessary to initialize this in some way.

Solution

Implement a class #initialize method to set the initial values of the class variables. Dolphin arranges for #initialize to be automatically sent to any class that reponds to it when the class is installed from a CLS file or package. However, you will need to send it explictly when the class has just been created, and at any time after the initialization method is changed.

Unlike Instance Initialization, the initialize method must not forward #initialize to super since Dolphin may then cause the code to be executed several times when the class is installed into a new image.

Consequences

Sometimes the initialization of a class variable may not be possible due a dependancy issue. That is, it needs to be set up with an instance of some other class that cannot be guaranteed to be available at the class initialization time. In this case employ Lazy Initialization of the variable instead.

Known Uses

Class Behavior holds a number of class variables that hold masks for an instance specification flag. These are initialized when the class is.

initialize
	"Initialize the class variables of the receiver"

	MournerMask := 16r0400.
	IndirectMask	:= 16r0800.
	VariableMask	:= 16r1000.
	PointersMask := 16r2000.
	NullTermMask	:= 16r4000.
	SizeMask := 16r00FF.
	BasicSpecMask	:= 16r7FFF.	

	FundamentalShapeMask := VariableMask + PointersMask + SizeMask.
	ShapeMask := FundamentalShapeMask + NullTermMask.
	BytesSubMask	:= NullTermMask + IndirectMask

Related Patterns