Suffix Conditionals in Smalltalk
I’ve always been fascinated with the way conditionals are implemented
in Smalltalk. Rather than having built-in if
/then
/else
keywords, Smalltalk uses polymorphism. The Boolean
subclasses
True
and False
simply implement #ifTrue:
, #ifFalse:
,
#ifTrue:ifFalse:
, #and:
, #or:
, etc. appropriately for
themselves. This is a brilliant design, and understanding it got me
closer to really understanding Smalltalk.
Using these methods, you write conditional code like so:
In contrast, Ruby does use if
and else
keywords, as well as
unless
. Interestingly, it also provides suffix versions of these
keywords, so you can write:
This makes for a relatively terse one-liner that sometimes reads better than the way we traditionally write conditionals.
I find that I sometimes want the focus of a conditional statement to be on the action, rather than the condition. In that case I prefer the suffix form, but Smalltalk doesn’t have that form built in. It’s simple enough to add, though, so I did.
SuffixConditionals
provides #if:
and #unless:
methods on BlockClosure
that allow
writing suffix-style conditional statements in Visualworks Smalltalk:
or:
I don’t use these forms everywhere, because they don’t always read
better than the standard #ifTrue:
/#ifFalse:
variants. Also, the
standard variants are optimized in the VM so using the suffix variants
will introduce a slight performance penalty. I tend to prefer
expressive code until my profiler tells me I have a problem, so I’m
not worried about that too much.
SuffixConditionals’ primary home is the Cincom Public Store Repository. Check there for the latest version. I’ve put a snapshot of the current version of SuffixConditionals on GitHub. I’ve also submitted it for inclusion as a contributed package in a forthcoming Visualworks release.
SuffixConditionals was developed in VW 7.9.1, but is intended to be compatible with any version of Visualworks Smalltalk. The code could also easily be ported to any other Smalltalk.
SuffixConditionals is released under the MIT license.