When is initialize invoked in smalltalk?
Asked Answered
T

2

5

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?

Tensity answered 27/9, 2013 at 1:45 Comment(0)
S
9

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.

Speedboat answered 27/9, 2013 at 3:29 Comment(0)
A
1

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.

Around answered 27/9, 2013 at 9:4 Comment(2)
Note that the class (which is an object A) cannot directly write into an instance (which is another object B). The only way for A is to send a message to B. In all cases A has to first create B, then initialize properly. A constructor for me is something that performs the two ops (create+initialize) atomically. When new sends initialize, the unitialized basicNew is hidden, so we can maintain the illusion of proper constructor. To avoid initializing twice for other messages like x:y: we rather send Point basicNew setX:y:, though for Point, Integer>>@ is often a primitive and thus atomic.Magdalenemagdalenian
Yes, and probably the Smalltalk Kent Beck did use when writing the Smalltalk Best Practice Patterns did not call #initialize via #new by default.Around

© 2022 - 2024 — McMap. All rights reserved.