Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Classes and Objects

Initialize and Creating Instances in Smalltalk: new, Constructors

Learn how Pharo creates objects: new calls initialize, how to write class-side instance creation methods like owner:, validate arguments, and avoid the classic trap of overriding new.

An object that starts life with nil in every instance variable is fragile. Every method has to guard against nil, and callers must remember to set things up in the right order. Smalltalk's answer is simple: initialize sets the object up, and class-side creation methods are the constructors. This lesson explains how the pieces fit and what to avoid.

Smalltalk code is read-only here. The stand-ins run in JavaScript.

new calls initialize

In Pharo, Object class >> new allocates an instance and then sends it initialize:

SMALLTALK
Behavior >> new
    ^ self basicNew initialize

So if you implement initialize in your class, every new produces a ready object:

SMALLTALK
BankAccount >> initialize
    super initialize.
    balance := 0

Now BankAccount new balance answers 0 with no ifNil: needed. Two rules:

  1. Start with super initialize, so superclasses can set up their own variables.
  2. Initialise every instance variable that has a sensible default: collections, counters, flags.
SMALLTALK
ShoppingCart >> initialize
    super initialize.
    items := OrderedCollection new.
    discount := 0

Do not rely on nil meaning "empty collection". An uninitialised items leads to nil does not understand #add:.

Class-side instance creation

Often an object needs required data. Define class-side methods (in the "class side" toggle of the browser, written BankAccount class >> ...) with intention-revealing names:

SMALLTALK
BankAccount class >> owner: aString
    ^ self new
        setOwner: aString;
        yourself

BankAccount >> setOwner: aString
    owner := aString

Usage:

SMALLTALK
| account |
account := BankAccount owner: 'Ada'.

Notes:

  • On the class side self is the class, so self new creates an instance of the receiver. This respects subclasses: SavingsAccount owner: 'Bo' answers a SavingsAccount.
  • yourself ends the cascade so the method returns the new account, not the result of setOwner: (see Cascades).
  • Name the method after what you pass: owner:, from:to:, named:, withAll:.
  • Keep the setter private (protocol private or initialization) when outsiders should not change the value later.

Classic examples in the system: Point x: 3 y: 4, Array new: 5, OrderedCollection withAll: #(1 2), Date year: 2025 month: 1 day: 1.

sequenceDiagram
    participant C as Caller
    participant K as BankAccount (class)
    participant I as new instance
    C->>K: owner: 'Ada'
    K->>K: self new
    K->>I: basicNew
    K->>I: initialize
    K->>I: setOwner: 'Ada'
    K-->>C: the account

The class-side method creates the instance, new triggers initialize, and only then is the required data injected.

Validating on creation

Put checks into the class-side method or the setter, so invalid objects never exist:

SMALLTALK
BankAccount class >> owner: aString
    aString isEmptyOrNil ifTrue: [ ^ self error: 'Owner required' ].
    ^ self new setOwner: aString; yourself

You can also use Error signal:, self assert: condition or a custom exception class.

Traps

Do not override new unless you have to. In older code you will find:

SMALLTALK
BankAccount class >> new
    ^ super new init

It works, but it fights Pharo's built-in new -> initialize, and when a subclass also overrides it you can run initialisation twice. In Pharo, implement initialize and stay with the default new.

Call super initialize. Forgetting it means inherited variables remain nil. Newer Pharo versions warn about it in the code critic.

Don't do heavy work in initialize. Opening files, calling services or reading databases there makes tests slow and failures confusing. Do the heavy work in an explicit method (open, connect).

Order matters in initialize. If initialize calls a method that uses a variable you set later, you get nil. Set the variables first.

= and hash: part of being a good citizen

If your objects will live in a Set or be keys of a Dictionary, define equality properly. Two points are equal if their coordinates are equal, so:

SMALLTALK
Point3D >> = other
    ^ self class = other class
        and: [ x = other x and: [ y = other y and: [ z = other z ] ] ]

Point3D >> hash
    ^ x hash bitXor: (y hash bitXor: z hash)

Rule: objects that are equal must have equal hashes. Always override both or neither.

JS Stand-in: constructor and initialisation order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: equal objects need equal hashes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does new do in Pharo?

    Behavior>>new is basicNew followed by initialize.
  2. 2. What should the first statement of your initialize method be?

    Calling super initialize lets superclasses set up their own variables.
  3. 3. In BankAccount class >> owner: aString ^ self new setOwner: aString; yourself, why is yourself needed?

    A cascade answers the value of its last message. yourself answers the receiver.
  4. 4. If two objects are equal (=), what must be true about their hash?

    Hashed collections rely on equal objects having equal hashes, so override = and hash together.

Summary

  • Pharo's new calls initialize; implement initialize (starting with super initialize) to set defaults.
  • Class-side methods such as owner: are the constructors; use self new ... yourself.
  • Validate inputs early so invalid objects never exist.
  • Avoid overriding new, avoid heavy work in initialize, and keep initialisation order in mind.
  • Override = and hash together for objects used in sets and dictionaries.

Next: Inheritance, super and Polymorphism