Category:Smalltalk: Difference between revisions

Line 394:
 
=== Control Structures ===
As mentioned above, these are defined as messages and their implementation is found in the corresponding receiver classes. TheFor followingillustration, here is onlyhow aconditional tiny subsetexecution ('if-then-else') thereis implemented in Smalltalk. There are virtuallytwo hundredsboolean ofobjects usesnamed "true" and "false", which are singletons of blockscorresponding forclasses controlnamed structures"True" inand "False" (both inherit from Boolean, which inherits from Object). It is essential, that these are singletons, and that typical relational operators like "<", ">" etc. return one of thethese systemtwo.
<br>Then, in the True class, define a method:
<lang smalltalk>True
ifYouAreTrueThenDo: arg1 ifNotThenDo: arg2
^ arg1 value
 
False
ifYouAreTrueThenDo: arg1 ifNotThenDo: arg2
^ arg2 value
Now, we can send this message to a boolean, and pass the code to be executed conditionally as a lambda block:
<lang smalltalk>(a > 0) ifYouAreTrueThenDo:[ 'positive'printCR ] ifNotThenDo:[ 'negative' printCR ]</lang>
 
In this style, all of Smalltalk's control structures, loops, enumeration, stream readers and event the exception handling constructs are built. And since every class is open, you can easily add additional convenient control functions.
 
The following is only a tiny subset - there are virtually hundreds or thousands of uses of blocks for control structures in the system.
Typical are:
<lang smalltalk>boolean ifTrue: [ block providing value if boolean is true ]
Anonymous user