Navigation:  Tutorials > Beginners Guide to Smalltalk > Control Flow >

Controlling the Flow of Execution

Previous pageReturn to chapter overviewNext page

Now let's put these boolean expressions to some good use. Based on the result of a particular expression we might want to execute or skip a piece of code. This is how it's done in Smalltalk (you don't need to Display it):

(simon radius > charlie radius) ifTrue: [

       MessageBox notify: 'Simon is bigger than Charles'].

 

What's going on here? The boolean expression testing the two radii answers true (because we grew simon slightly earlier). Like everything else, a boolean value such as true or false is still an object and is therefore capable of handling messages sent to it. Here we send it #ifTrue: which takes as its parameter a block of code to execute in the case that the receiver is indeed true. The block of code is enclosed in square brackets []. If the receiver is false then the block does not get executed.

There are also additional messages that can be sent to boolean objects along similar lines.

"#ifFalse:"

(charlie color=Color green) ifFalse: [

       "If charlie is not green make him so"

       charlie color: Color green ].

 

"#ifTrue:ifFalse:"

(Time now hours>6)

       "Turn charlie off at night"

       ifTrue: [charlie color: Color yellow]

       ifFalse: [charlie color: Color black].

 

This message offers the choice between executing one of two blocks of code. You must remember, though, that #ifTrue:ifFalse: is a single keyword message taking two parameters. Hence there must not be a dot separator after the first block since this would terminate the statement at this point (and you'll subsequently receive an error from the Dolphin compiler).

For convenience, there is also the reverse message:

"#ifFalse:ifTrue:"

(Time now hours>6)

       "Turn charlie off at night"

       ifFalse: [charlie color: Color black]

       ifTrue: [charlie color: Color yellow].