Smalltalk has no “if” statement

section of parrot logo 1section of parrot logo 2section of<br />
parrot logo 3section of parrot logo 4section of parrot logo 5section of parrot logo 6

If I had to summarize everything I love about Smalltalk into one statement, it would be that one. Smalltalk has no “if” statement, and it has no “for” statement, no “while” statement… no control of flow statements at all.

Some of the audience may be thinking that this is evidence confirming their suspicions that Smalltalk is weird, but what I’m going to tell you is this:

An “if” statement is an abomination in an Object Oriented language.

Why? Well, an OO language is composed of classes, objects and methods, and an “if” statement is inescapably none of those. You can’t write “if” in an OO way. It shouldn’t exist. Conditional execution, like everything else, should be a method. A method of what? Boolean.

Now, funnily enough, in Smalltalk, Boolean has a method called ifTrue:ifFalse: (that name will look pretty odd now, but pass over it for now). It’s abstract in Boolean, but Boolean has two subclasses: True and False. The method is passed two blocks of code. In True, the method simply runs the code for the true case. In False, it runs the code for the false case. Here’s an example that hopefully explains:

(x >= 0) ifTrue: [
'Positive'
] ifFalse: [
'Negative'
]

You should be able to see ifTrue: and ifFalse: in there. Don’t worry that they’re not together.

The expression (x >= 0) evaluates to true or false. Say it’s true, then we have:

true ifTrue: [
'Positive'
] ifFalse: [
'Negative'
]

I hope that it’s fairly obvious that that will produce ‘Positive’.

If it was false, we’d have:

false ifTrue: [
'Positive'
] ifFalse: [
'Negative'
]

That produces ‘Negative’.

OK, that’s how it’s done. What’s so great about it? Well, in what other language can you do this? More seriously, the answer is that there aren’t any special cases in this language. Everything can be done in an OO way, and everything is done in an OO way.

Quite crucial to this is the fact that you can pass bits of code as parameters to methods. If that sounds interesting, then carry on to: Code is an object.

If you’re thinking that the syntax is just too weird, then maybe you should instead look at: [Methods with named parameters].