Stupid Question?

Zulq Alam me at
Wed Jan 16 15:46:43 UTC 2008

Hi Richard,

The instance variables and methods, including accessors, exist when the 
object is created. They do not depend on the initialize method. Thus you 
can access any instance variable or call any defined method, such as 
accessors, at any time after creation. Whether they have a value or 
return anything useful depends on your object and how you *chose* to 
initialize it.

The use of #initialize is a convention to set-up object state *after* 
the object has been created. You do not have to stick to this. For 
example, consider the Point class.

On the class side it defines:

x: xInteger y: yInteger
	"Answer an instance of me with coordinates xInteger and

	^self basicNew setX: xInteger setY: yInteger

And on the instance side:

setX: xValue setY: yValue

	x _ xValue.
	y _ yValue

So, effectively we have two constructor methods, one on the class side 
which passes parameters to the one on the instance side which does all 
the work.

In this case, the #initialize methods is never called because the class 
side constructor sends #basicNew instead of #new. This makes more sense 
if we look at how #new is defined on Behaviour.

	"Answer a new initialized instance of the receiver (which is a
	class) with no indexable variables. Fail if the class is

	^ self basicNew initialize

Some people use #initializeWith???: type methods instead of set???: 
methods. I'm not sure which is better.

Having said all that, I often do what Norbert suggests and just call 
setter methods from the class side constructor:

MyObject class>>on: aStream
    ^ self new
       stream: aStream;

This is great if I just want to set some instance variables and run. The 
possible downside is you may not want to have the setter #stream:


Richard Eng wrote:
> I have a stupid question:  How do you pass information into the #initialize
> method at object creation time? You can't use any of the instance methods or
> accessors because they don't yet exist! So how do you pass information in?
> Thanks,
> Richard

More information about the Squeak-dev mailing list