Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Classes and Objects

Defining Classes and Methods in Pharo Smalltalk

Create your first Pharo class with the fluid class definition syntax, add instance variables and methods in the System Browser, write accessors, and understand method categories and the Class >> selector notation.

A class is a blueprint that says which instance variables an object has and which methods it understands. In Pharo you define classes by sending a message to an existing class, and you write methods in the System Browser one at a time. This lesson builds a small BankAccount class from scratch.

The Smalltalk code below is read-only (no Smalltalk runner on this site), and a JavaScript stand-in mirrors the design so you can run it.

Defining a class

Pharo (version 12 and later) offers the fluid class definition:

SMALLTALK
Object << #BankAccount
    slots: { #owner. #balance };
    package: 'Bank'.

Read it as a message: to the superclass Object, send << with the symbol #BankAccount, then configure the new class with slots: (instance variables) and package: (where the class is filed), all as a cascade-like chain. Running this code in a Playground creates the class. In older images and in many books you will meet the long form:

SMALLTALK
Object subclass: #BankAccount
    instanceVariableNames: 'owner balance'
    classVariableNames: ''
    package: 'Bank'.

Both do the same thing. More options exist: sharedVariables: for class variables, tag: for sub-packages, traits: to compose traits.

In practice you often use the class creation template that the System Browser shows in its source pane when you select a package: edit it, accept it (Ctrl+S), and the class appears.

Adding methods

In the browser, select the class, pick a protocol (a category), and write a method in the bottom pane. The pane shows a template:

SMALLTALK
messagePattern
    "comment"
    | temporaries |
    statements

Write, for example:

SMALLTALK
balance
    ^ balance ifNil: [ 0 ]

and press Ctrl+S (Cmd+S) to accept: the method is compiled immediately and available to every existing instance. In books and documentation the notation BankAccount >> balance names this method, and BankAccount class >> new names a method on the class side. These are labels for humans; they are not the syntax you type in the browser.

You can also define a method from code (handy for scripts and tests):

SMALLTALK
BankAccount compile: 'balance ^ balance ifNil: [ 0 ]' classified: 'accessing'.

Methods for the bank account

Here is the full set, one method per entry (the browser requires the pane to hold one method at a time):

SMALLTALK
BankAccount >> owner
    ^ owner

BankAccount >> owner: aString
    owner := aString

BankAccount >> balance
    ^ balance ifNil: [ 0 ]

BankAccount >> deposit: anAmount
    anAmount <= 0 ifTrue: [ ^ self error: 'Deposit must be positive' ].
    balance := self balance + anAmount

BankAccount >> withdraw: anAmount
    anAmount > self balance ifTrue: [ ^ self error: 'Insufficient funds' ].
    balance := self balance - anAmount

BankAccount >> printOn: aStream
    aStream nextPutAll: 'Account(', owner asString, ': ', self balance printString, ')'

Notes:

  • Accessors are plain methods named after the variable (owner, owner:). No get or set prefix.
  • self error: 'text' raises an exception (see the testing chapter for how to test for it).
  • Inside a method, other methods of the same object are called through self, including self balance. This keeps room for subclasses to change them.
  • printOn: controls how the object is displayed in inspectors and with Print it (see Class side, class variables and printOn:).

Using the class

SMALLTALK
| account |
account := BankAccount new.
account owner: 'Ada'.
account deposit: 100.
account withdraw: 30.
account balance.    "-> 70"
account.            "-> Account(Ada: 70)  (using printOn:)"
account withdraw: 500.   "-> opens the debugger: 'Insufficient funds'"

new is inherited from Behavior; it allocates an instance with all instance variables set to nil. That is why balance must cope with nil. The next lesson, Initialize and creating instances, shows the proper fix.

Protocols

Methods are grouped into protocols in the browser: accessing, testing, initialization, printing, private, actions. They are labels only, but they are the conventional table of contents of a class, so name them well. Pharo also has the convention of a private protocol for helpers that other classes should not call (not enforced by the language).

flowchart TD
    P["Package: Bank"] --> C["Class: BankAccount"]
    C --> V["Instance variables: owner, balance"]
    C --> A["Protocol: accessing<br/>owner, balance"]
    C --> B["Protocol: actions<br/>deposit:, withdraw:"]
    C --> D["Protocol: printing<br/>printOn:"]

A package contains classes; a class has instance variables and protocols that group methods.

Documentation: class comments

Every class should have a comment, written in the browser's comment tab. A good first line says what the class is for. Pharo shows it in tooltips and in generated documentation.

JS Stand-in: the BankAccount class

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

No output.

JS Stand-in: adding a method to a live class

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. In the fluid class definition Object << #Foo slots: { #a }; package: 'P', what does slots: define?

    slots: lists the instance variables. Class variables use sharedVariables:.
  2. 2. What does the notation BankAccount >> balance mean?

    Class >> selector is how books and documentation refer to a method; you type only the method body in the browser.
  3. 3. Why does a freshly created BankAccount new need balance ifNil: [ 0 ]?

    Without an initialize method, instance variables are nil. The next lesson shows how to initialize them.
  4. 4. What are protocols?

    Protocols are labels such as accessing and printing. They do not change behaviour.

Summary

  • Define a class by sending << (or subclass:instanceVariableNames:...) to its superclass, naming slots and a package.
  • Write methods one at a time in the System Browser; accept with Ctrl+S and they are live immediately.
  • Class >> selector is the documentation notation for a method.
  • Accessors use the variable's name; use self to call your own methods.
  • Group methods in protocols and comment each class.

Next: Initialize and Creating Instances