Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 38 ยท Syntax and Messages

Control Flow with Messages: ifTrue:, whileTrue:, to:do: in Smalltalk

Smalltalk has no if or for keywords. Learn conditionals, loops, ifNil:, and:/or:, to:do:, timesRepeat:, whileTrue: and early exit, all expressed as messages that take blocks.

Every language needs ways to choose and to repeat. Most give you keywords for them. Smalltalk gives you messages: you ask a Boolean to choose, you ask a number to count, you ask a block to repeat itself. The result reads fluently once you are used to it, and it means you can add your own control structures as ordinary methods.

Smalltalk code in this lesson is read-only; JavaScript stand-ins are runnable.

Conditionals

SMALLTALK
age >= 18
    ifTrue: [ 'adult' ]
    ifFalse: [ 'minor' ].

ifTrue:ifFalse: is sent to the Boolean age >= 18, and each argument is a block. The conditional is an expression with a value, so you can assign it:

SMALLTALK
| label |
label := age >= 18 ifTrue: [ 'adult' ] ifFalse: [ 'minor' ].

Variants:

SMALLTALK
x > 0 ifTrue: [ Transcript show: 'positive'; cr ].
x > 0 ifFalse: [ Transcript show: 'not positive'; cr ].
x isNil ifTrue: [ ... ] ifFalse: [ ... ].
x ifNil: [ 0 ].                 "value of x, or 0 when x is nil"
x ifNotNil: [ :v | v + 1 ].
x ifNil: [ 0 ] ifNotNil: [ :v | v * 2 ].

A conditional without the branch that was taken answers nil (for example 3 > 4 ifTrue: ['x'] answers nil).

Combining conditions

SMALLTALK
(a > 0) and: [ b > 0 ].         "b > 0 is evaluated only if a > 0"
(a > 0) or: [ b > 0 ].
(a > 0) & (b > 0).              "both sides are always evaluated"
(a > 0) | (b > 0).
a > 0 and: b > 0.               "works only if the argument is a Boolean; prefer blocks"

Use and: and or: with blocks to get short-circuit behaviour. Don't write a > 0 and: [ ... ] without parentheses around a > 0; precedence works in your favour here (binary > first), but the parentheses make intent clear.

Comparison messages

SMALLTALK
3 = 3.  3 ~= 4.  3 < 4.  3 between: 1 and: 5.
'abc' < 'abd'.      "strings compare alphabetically"
x isZero.  x isEmpty.  x notEmpty.  x isNil.  x notNil.

Choosing among many cases

Smalltalk has no switch. Typical solutions are a dictionary of blocks, or better, polymorphism: let each object answer the message in its own way (see Inheritance, super and polymorphism).

SMALLTALK
| actions |
actions := Dictionary new.
actions at: #add put: [ :a :b | a + b ]; at: #mul put: [ :a :b | a * b ].
(actions at: #add) value: 3 value: 4.     "-> 7"

Loops

Counting

SMALLTALK
1 to: 5 do: [ :i | Transcript show: i printString; cr ].
10 to: 1 by: -3 do: [ :i | ... ].      "10 7 4 1"
5 timesRepeat: [ Transcript show: '*' ].

to:do: is a keyword message sent to a number; the block takes the counter. The compiler turns it into a fast loop, but semantically it is a message send.

Iterating over collections

SMALLTALK
#(3 1 2) do: [ :each | Transcript show: each printString; cr ].
#(3 1 2) doWithIndex: [ :each :i | ... ].
#(3 1 2) reverseDo: [ :each | ... ].

This is the style used most of the time; we return to it in Iteration and enumeration.

Conditional loops

SMALLTALK
| n |
n := 1.
[ n < 100 ] whileTrue: [ n := n * 2 ].
n.      "-> 128"

[ n > 1 ] whileTrue: [ n := n // 2 ].
[ n >= 10 ] whileFalse: [ n := n + 1 ].
[ Transcript show: 'once'; cr. false ] whileTrue.   "runs the block, loops while it answers true"

whileTrue: is sent to a block (the condition), with a block for the body. repeat loops forever until you return or an exception ends it:

SMALLTALK
[ line := stream next. line isNil ifTrue: [ ^ self ]. self process: line ] repeat.

Leaving early

Inside a method, use ^:

SMALLTALK
findFirstNegative: numbers
    numbers do: [ :each | each < 0 ifTrue: [ ^ each ] ].
    ^ nil

The ^ inside the block returns from the method. Often the library already has what you need: numbers detect: [ :each | each < 0 ] ifNone: [ nil ].

Writing your own control structure

Because control flow is message sending, you can create new structures. If a class defines the method:

SMALLTALK
Object >> unless: condition do: aBlock
    condition ifFalse: [ ^ aBlock value ]

then self unless: x > 0 do: [ ... ] works exactly like built-in structures. That is the kind of extension JavaScript's if cannot offer.

JS Stand-in: control flow as messages

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

No output.

JS Stand-in: and: is lazy, & is not

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

No output.

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What kind of thing is ifTrue:ifFalse: in Smalltalk?

    True and False implement the message; there is no special if syntax.
  2. 2. What is the difference between (a > 0) and: [ b > 0 ] and (a > 0) & (b > 0)?

    The block makes the evaluation lazy, giving short-circuit behaviour.
  3. 3. Which expression counts from 10 down to 1 in steps of 3?

    to:by:do: accepts a negative step.
  4. 4. Where is the receiver of whileTrue: ?

    [ cond ] whileTrue: [ body ] sends whileTrue: to the condition block.
  5. 5. What does a conditional like 3 > 4 ifTrue: [ 'x' ] answer?

    When the branch is not taken and no alternative is given, the answer is nil.

Summary

  • Conditions and loops are messages with block arguments: ifTrue:ifFalse:, and:, or:, whileTrue:, to:do:, timesRepeat:.
  • ifNil: and ifNotNil: handle missing values elegantly.
  • Use and:/or: with blocks for short-circuiting; &/| always evaluate both sides.
  • There is no switch; prefer polymorphism or a dictionary of blocks.
  • Return from a method with ^, even from inside a loop block; you can also define your own control structures.

Next: Variables, Scope and Pseudo-variables