Smalltalk language does not offer with his standard classes a switch-case mechanism. Here is an easy way to implement such a mechanism.
The first step will be to create a class
Switch as subclass of class
Object and to define three variables:
value will hold the object for which the switch is made. The variable
satisfied tells us, if any of the case conditions are met. The variable
response will hold the result of the operation, which will be made in case of fulfillment of the conditions of any case.
Next we define a class method
for: which creates an instance of the class
To avoid having to initialize the variable
false, we define a method
isSatisfied, which returns
true only if the variable
Now we create methods
And now we can write:
For such a simple test block as above, we can create a very useful method in class
So our previous example will look like this:
We can also define an identity version of this method for fast comparing of symbols or classes:
And we can simplify searching in collections:
All of this looks good, but someone would like it even easier - instead of writing
Switch for: aValue simply write
aValue switch. To do this we add the switch method to the class Object.
And our previous example can be written as follows:
switch presented above can also be defined as follows:
Now it is possible to use the following syntax:
Besides, this implementation allows to use an instance of the class ValueHolder in the switch-case structure. The method switch can now be sent directly to such an object.
In the above switch-case mechanism we can also remove the variable
satisfied. We will then perform several blocks satisfying the case conditions, just as it does in C.
Przemysław Nieściór & Wacław Hołub, 02.06.2002
or on GitHub: