| Edit | Rename | Changes | History | Upload | Download | Back to Top |
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:
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:
| Edit | Rename | Changes | History | Upload | Download | Back to Top |