Newbie q

Brian Brown rbb at techgame.net
Fri Sep 26 15:10:42 UTC 2003


On Friday, Sep 26, 2003, at 06:52 America/Denver, Matej Kosik wrote:

> On Fri, Sep 26, 2003 at 09:25:32AM +0200, Brent Pinkney wrote:
>>>
>>> anInstanceVar
>>> anInstanceVar ifNil: [
>>> anInstanceVar _ someInitializationCode.
>>> ].
>>> ^ anInstanceVar
>>>
>> This is more terse:
>>
>> anInstanceVar
>>
>> 	^ anInstanceVar ifNil: [ anInstanceVar := someInitializationCode ]
>
> Someone might prefer this approach. I have seen this approach regularly
> used in the code generated by VisualWorks GUI builder and (to my
> disappointment) also in some random places in Morphic classes.
>

[snip]

> I do not like it. The trivial method which should do nothing more
> but return the value of the appropriate instance variable is spoiled
> by some superfluous stuff.
>
> I always initialize instance variables in "constructors".
>
> I didn't see that ifNil: practise anywhere within the Purple Book.
> Fortunatelly the method Point>accessing>x does not look like this:
>
>   ^x ifNil: [x := 0]
>
> but thankfully like this
>
>   ^x
>
> I like it.
>

Welcome Phil, and Hello Matej ;-)

I don't know about the Purple Book, but I find both the Lazy 
Initialization and what your are talking about Matej, Common State in 
the Smalltalk Best Practices Book (Kent Beck).

The principal difference is whether you know beforehand if a variable 
is likely to be used and want to save space/resources if it won't. I 
typically use Lazy Initialization for simple instance vars like strings 
and numbers and even Collections, but use constructors and initialize 
methods for more complex objects that I know will be used.

;-)



More information about the Squeak-dev mailing list