Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Testing and Patterns

Design Patterns in Smalltalk

See how classic design patterns look in Smalltalk, where blocks and polymorphism often replace boilerplate: Strategy, State, Command, Template Method, Visitor and Null Object, with runnable JavaScript stand-ins.

Many of the famous design patterns were first described using Smalltalk code, and several are simply part of the language. Because blocks are objects, and because every object is polymorphic, a lot of the ceremony needed in other languages disappears. This lesson looks at six patterns, shows the idiomatic Smalltalk shape (read-only), and gives a runnable JavaScript stand-in for each idea.

The common thread: replace a conditional with polymorphism. In Smalltalk the first question is "which object should answer this message?" rather than "what is the type of this value?".

Strategy: pass a block

A strategy is an interchangeable algorithm. Where Java needs an interface and one class per variant, Smalltalk can use a block:

SMALLTALK
Invoice >> totalUsing: taxStrategy
    ^ items sum: [ :each | taxStrategy value: each ]

invoice totalUsing: [ :item | item price * 1.2 ].
invoice totalUsing: [ :item | item price ].

When a strategy needs several operations or its own state, use real classes that share a protocol.

JS Stand-in: Strategy with functions

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

No output.

State: delegate to a state object

Instead of a case on a status field, give each state its own class and delegate:

SMALLTALK
Door >> open
    state := state open: self

ClosedState >> open: aDoor
    ^ OpenState new

OpenState >> open: aDoor
    ^ self    "already open"

Adding a state means adding a class, not editing every method that tests the status.

JS Stand-in: State pattern

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

No output.

Template Method: the hook is the subclass

The superclass defines the skeleton, and subclasses override the steps. This is everyday Smalltalk (read-only):

SMALLTALK
Report >> render
    ^ String streamContents: [ :s |
        s nextPutAll: self header; cr.
        self rows do: [ :r | s nextPutAll: r; cr ].
        s nextPutAll: self footer ]

SalesReport >> header
    ^ 'Sales'

Report leaves header and rows unimplemented, usually with self subclassResponsibility, which fails loudly if a subclass forgets one.

Command: a block or an object

A command packages an action so it can be queued, logged or undone. A block is the smallest command; a class is needed when you want undo:

SMALLTALK
undoStack addFirst: (Command do: [ doc insert: 'x' ] undo: [ doc removeLast ]).
JS Stand-in: Command with undo

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

No output.

Visitor: double dispatch

Smalltalk's classic technique is double dispatch: the element sends a message to the visitor that names its own type, so no type tests are needed:

SMALLTALK
Circle >> accept: aVisitor
    ^ aVisitor visitCircle: self

Square >> accept: aVisitor
    ^ aVisitor visitSquare: self

AreaVisitor >> visitCircle: c
    ^ Float pi * c radius squared

The same idea makes Integer + Float work: 3 + 4.5 asks the argument to add itself via 4.5 adaptToInteger: 3 andSend: #+. The first dispatch picks the receiver's class, the second picks the argument's.

JS Stand-in: Visitor by double dispatch

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

No output.

Null Object

Instead of checking nil everywhere, return an object that does nothing. The technique also appears in doesNotUnderstand: and proxies. Prefer an explicit class (NullLogger) with real methods when you can.

Observer

Smalltalk's classic observer is the dependents mechanism; modern Pharo uses announcements, which is the next lesson.

flowchart TB
  subgraph Replace_the_if
    Q["if kind = A ... else ..."] --> P["send the message<br/>to a polymorphic object"]
  end
  P --> S["Strategy: block"]
  P --> T["State: object per state"]
  P --> V["Visitor: double dispatch"]

Most patterns here are the same move: let an object decide instead of testing its type.

Choosing wisely

A pattern is a name for a solution to a recurring problem, not a goal. Use it when you have the problem. Too many small classes is also a cost; a block is often enough. Tests from SUnit let you introduce patterns later, when the second or third variant appears.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is the usual lightweight Strategy in Smalltalk?

    Blocks are objects, so they carry the interchangeable algorithm.
  2. 2. What does double dispatch solve?

    Each send selects a method by one class; two sends select by two.
  3. 3. What is self subclassResponsibility for?

    It signals an error if the method is reached, so a forgotten override fails loudly.
  4. 4. What is the main idea behind State?

    Polymorphism replaces conditionals on a status field.

Summary

  • Many patterns collapse to blocks and polymorphism in Smalltalk.
  • Strategy is a block, State is delegation, Template Method uses subclassResponsibility, Visitor uses double dispatch.
  • Command needs a class only when you want undo or logging.
  • Use a pattern when the problem appears, and back it with tests.
  • Smalltalk snippets are read-only; the JavaScript versions are stand-ins.

Next: Announcements and Observers