Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท Classes and Objects

Class Side, Class Variables and printOn: in Smalltalk

Learn the class side of a Smalltalk class: class methods, class variables, class-side instance variables, singletons, and how printOn:, displayString and storeOn: control how objects are shown.

A Smalltalk class is itself an object, so it can have methods, variables and state. The methods you write for the class live on its class side, and they are used for creating instances, keeping registries and offering utility operations. This lesson also covers printOn:, the method that decides how any object appears in inspectors and in Print it, which you will override in nearly every class you write.

Smalltalk code is read-only on this site; JavaScript stand-ins run.

Instance side and class side

In the browser, the Class side button flips to the methods the class itself understands. In documentation Foo >> bar is an instance method and Foo class >> bar is a class method.

SMALLTALK
Date today.                 "class method: Date class >> today"
Date today dayOfWeek.       "instance method: Date >> dayOfWeek"
OrderedCollection new.      "class method"
OrderedCollection new add: 3.   "instance method"

Why a separate side? Because the receiver of Date today is the class Date, and the receiver of dayOfWeek is an instance of Date. Two kinds of receiver, two method dictionaries. The class side is where "factory" and "global operation" methods go.

flowchart LR
    I["aCounter<br/>(instance)"] -->|"class"| C["Counter<br/>(class object)"]
    C -->|"class"| M["Counter class<br/>(metaclass)"]
    M -->|"class"| MM["Metaclass"]

An instance knows its class, the class knows its metaclass; class-side methods live in the metaclass. Chapter 5 explores this in depth.

Class variables

A class variable is one variable shared by the class and all of its instances (and by subclasses). Declare it with sharedVariables::

SMALLTALK
Object << #Ticket
    slots: { #number };
    sharedVariables: { #LastNumber };
    package: 'Support'.

Ticket class >> initialize
    LastNumber := 0

Ticket class >> nextNumber
    LastNumber := LastNumber + 1.
    ^ LastNumber

Ticket >> initialize
    super initialize.
    number := self class nextNumber

Ticket >> number
    ^ number

Ticket new number answers 1, the next Ticket new answers 2. The class-side initialize runs when the class is loaded (and when you run Ticket initialize yourself). Class variable names begin with an uppercase letter.

Remember: shared state is global state. It is convenient for counters and caches, but it makes testing harder, so keep it small and hidden behind class methods.

Class-side instance variables

Each class can also have its own private instance variables, not shared with subclasses. You declare them on the class side (Ticket class >> instanceVariableNames: or Ticket class slots: ...). The difference: if Ticket has subclasses Support and Sales, a class variable LastNumber is shared by all three, but a class-side instance variable count is separate for each class. Use it for per-class registries.

The singleton pattern

SMALLTALK
Object << #AppConfig
    slots: { #settings };
    sharedVariables: { #Default };
    package: 'App'.

AppConfig class >> default
    ^ Default ifNil: [ Default := self new ]

AppConfig class >> reset
    Default := nil

AppConfig default always answers the same instance. Because this is global state, offer reset for tests and avoid sprinkling default calls through the whole code base.

printOn:: how objects present themselves

When you Print it, the system calls printString, which calls printOn: with a stream. The default prints the article and class name (a BankAccount). Override printOn: to be useful:

SMALLTALK
BankAccount >> printOn: aStream
    super printOn: aStream.
    aStream
        nextPutAll: '(';
        nextPutAll: owner asString;
        nextPutAll: ': ';
        print: self balance;
        nextPut: $)

Print it then shows a BankAccount(Ada: 70). The stream messages: nextPutAll: appends a string, nextPut: a single character, print: the print string of any object, << appends anything (aStream << 'x' << 5), tab, space and cr add whitespace.

Related methods:

Message Purpose
printString Developer view, built from printOn: (strings keep their quotes)
displayString User view; strings show without quotes, via displayStringOn:
printString: base Numbers in another radix, e.g. 255 printString: 16
storeString Code that rebuilds the object (storeOn:)
asString Conversion to String, defined by many classes

The inspector's title and the debugger's stack use printString, so a good printOn: makes debugging dramatically easier. Keep it short, free of side effects, and free of failures: an exception inside printOn: can break the debugger itself.

Utility class methods

Not every class is instantiated. Collections of related functions, constants and lookups are good class-side candidates:

SMALLTALK
Temperature class >> celsiusFromFahrenheit: f
    ^ (f - 32) * 5 / 9

Use these sparingly; if the same operation naturally belongs to an object (aTemperature asCelsius), put it on the instance side.

JS Stand-in: a class variable counter and singleton

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

No output.

JS Stand-in: printOn: with a stream

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 is the receiver of the message today in Date today?

    today is a class-side method; the receiver is the class object Date.
  2. 2. How do class variables differ from class-side instance variables?

    A class variable is one storage shared by the hierarchy; a class-side instance variable gets its own value in each class.
  3. 3. Which method should you override to customise Print it output?

    printString and the inspector call printOn: with a stream; override it and call super printOn: when appropriate.
  4. 4. What should a good printOn: avoid?

    An exception inside printOn: can make the debugger itself unusable. Keep it simple and safe.

Summary

  • Classes are objects; their methods live on the class side (Foo class >> bar) and are used for creation and utilities.
  • Class variables (sharedVariables:) are shared across the hierarchy; class-side instance variables are per class.
  • A singleton keeps its instance in a class variable behind a default method; provide reset for tests.
  • Override printOn: (using stream messages such as nextPutAll: and print:) to make objects readable in tools.
  • displayString is for users, printString for developers, storeString for rebuilding objects.

Next: Blocks and Closures