|
This post originated from an RSS feed registered with Agile Buzz
by James Robertson.
|
Original Post: Switch Statements
Feed Title: Cincom Smalltalk Blog - Smalltalk with Rants
Feed URL: http://www.cincomsmalltalk.com/rssBlog/rssBlogView.xml
Feed Description: James Robertson comments on Cincom Smalltalk, the Smalltalk development community, and IT trends and issues in general.
|
Latest Agile Buzz Posts
Latest Agile Buzz Posts by James Robertson
Latest Posts From Cincom Smalltalk Blog - Smalltalk with Rants
|
|
Every so often I see people ask "Why doesn't Smalltalk have a switch statement"? The simple answer is - "we don't need one". That usually ends up with something like this:
What if I'm parsing data that comes in with numeric (etc) values, and I want to take a different action on the different values?
Here's one approach to that problem - say you are going to get integers, and you need to execute a different action on receiving each:
setupActionDictionary
self actionDictionary: Dictionary new.
self actionDictionary at: 1 put: #handleOne.
self actionDictionary at: 2 put: #handleTwo.
...
And so on like that. So now, we can handle the receipt of the data like this:
executeActionFor: anID
action := self actionDictionary at: anID ifAbsent: [#defaultAction].
self perform: action.
actionID := self getNextIdentifier.
self executeActionFor: anID.
That's about it. For those of you who don't know Smalltalk, the keys in the dictionary are symbols (which can be mapped to method names). Hopefully, those names would be better than #handleOne (etc), but you get the idea.
Read: Switch Statements