Edit Rename Changes History Upload Download Back to Top

Quick definition of Lazy Initialization

Lazy initialization is postponing the initialization of a variable until it is really needed.

Lazy Initialization might be considered a pattern but it works at a lower level than most patterns.

All uninitialized variables in Smalltalk are consistently set to nil. If you want them to take on some other initial value, you have to do this explicitly at execution time. For instance variables this is most often done in an initialization method invoked from the class side #new method.

So, you will see:

new
    ^super new initialize
Though a better implementation would be:
new
    ^super basicNew initialize
There are a few disadvantages to this approach:

  1. If you add new instance variables, you have to update the #initialize method.
  2. Variables that are not frequently used are referenced and updated and could waste storage or give the garbage collector more work.
  3. If the initialization of an instance variable is expensive, doing so should be deferred until you are sure you need the variable.
Using lazy initialization requires the use of accessor methods. Also, nil must not be a "valid" value for the instance variable.

To do a lazy initialization, the accessor method for the variable checks to see if the variable is nil, and if so initializes it to some other, more meaningful value.

For example:

amount
    amount isNil ifTrue: [amount := 0.0 asValue].
    ^amount
That's all there is to it!

The requirements for lazy initialization are also good reasons to consider not using it:

  1. You must be willing to provide an accessor method for the instance variable. There are religious arguments for and against using accessors for all instance variable access. Your religion might preclude or your use of lazy initialization.
  2. If nil is a reasonable value for the variable to hold, you would have to initialize the variable to some other "uninitialized" value. And, at that point, you might as well just initialize it.
Back to quick start notes.


Edit Rename Changes History Upload Download Back to Top