Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is initialize invoked in smalltalk?

I have a class with instance variable 'a'.

When i create a new instance of the class using new, what is the order of the methods that are called?

How will the object know that it should call the initialize method?

If I create a class method to assign values to my instance variables, will the initialize still be called for other instance variables that are not invoked by my class method?

like image 372
Aditya Kappagantula Avatar asked Sep 27 '13 01:09

Aditya Kappagantula


2 Answers

initialize is usually called by the new method itself.

I believe the standard implementation is:

new
    ^self basicNew initialize

#basicNew is a primitive that just creates the object, but does no initialization. All instance variables will be nil after basicNew.

Note that the initialize method isn't called automatically in all implementations of Smalltalk (but I don't know which ones don't do it) so if you want to be properly portable, you should override #new in your classes to explicitly call it.

like image 70
Stuart Herring Avatar answered Nov 03 '22 01:11

Stuart Herring


Stuart answered it perfectly. But if you have still doubt about your second question:

If I create a class method to assign values to my instance variables, will the initialize still be called for other instance variables that are not invoked by my class method?

If you use something like Kent Beck's Constructor Parameter Method idiom for example in Pharo, where #initialize is sent from #new (as described by Stuart's answer):

Point class>>x: xNumber y: yNumber
    ^self new
        setX: xNumber
        y: yNumber

Point>>setX: xNumber y: yNumber
    x := xNumber.
    y := yNumber.
    ^self

Then first your initialize method will be called and only afterwards your Constructor Parameter Method will be called.

like image 34
MartinW Avatar answered Nov 03 '22 01:11

MartinW