December 4, 2022

Branching (Selection)


Most of the examples of Smalltalk code seen so far have been been sequential. Sequential execution of code simply means that each message expression (separated by a full stop) is executed one after the other. For example:

anAccount balance: 536870912.
anAccount overLimit: 1.
anAccount := Account new.
anAccount := holder: 'Bill Gates'.

There are two mechanisms by which this linear progression through a message series can be changed. These are called branching, or selection, and looping, or iteration. By employing the concept of branching we can follow different paths through a message expression series. In branching, a Boolean condition (i.e. an expression which returns either the object true or false) determines which path is taken. If there are two possible paths, the Smalltalk message ifTrue:ifFalse: is appropriate. E.g.

(anAccount balance > 1000000)
   ifTrue: [Dialog warn: 'Status A']
   ifFalse: [Dialog warn: 'Status B']

It may be the case that the situation demands something other than an "either or" algorithm. In other words only one path is required and this will be determined by the the Boolean condition. In these cases a simple ifTrue: or ifFalse: message is sufficient. E.g.

(self balance isNil)
   ifTrue: [self balance: 0]

Next page » Boolean messages

Previous page « Blocks
































































Up to top of page