. .


ST 4U 320: Using a CaseStatement in Smalltalk

December 12, 2012 11:15:01.801

Today's Smalltalk 4 You goes back to the CaseStatement sketch we did recently, and goes over when such a construct might be useful in Smalltalk. If you have trouble viewing it here in the browser, you can also navigate directly to YouTube. To watch now, click on the image below:

Case Statement.

If you have trouble viewing that directly, you can click here to download the video directly. If you need the video in a Windows Media format, then download that here.

You can also watch it on YouTube:

Having looked at a Case Statement sketch and at polymorphism, we'll turn back to the Case Statement idea - when might such a thing be useful in Smalltalk? There are times when you end up with a long section of #ifTrue:ifFalse: blocks - when dealing with keyboard shortcuts, or possibly return values from an external application. Consider this simple example:

"imagine that val is the return value from some external application"

| val cases |
val := ((EsRandom new next) * 10) rounded.
cases := CaseStatement case: 1 do: [Transcript show: '1'; cr].
	case: 2  do: [Transcript show: '2'; cr];
	case: 3  do: [Transcript show: '3'; cr];
	case: 4  do: [Transcript show: '4'; cr];
	case: 5  do: [Transcript show: '5'; cr];
	case: 6  do: [Transcript show: '6'; cr];
	case: 7  do: [Transcript show: '7'; cr];
	case: 8  do: [Transcript show: '8'; cr];
	case: 9  do: [Transcript show: '9'; cr].
cases switch: val default: [Transcript show: 'Not Found: ', val printString; cr].

Instead of a random number generator, imagine that the code coming back is from an external system call, and we need to do different things based on what came back. We could set up a polymorphic caller, using a dictionary matching numbers to symbols, and then performing the symbols - but that might actually be less clear than the code above. It's not often that you'll need a case statement in Smalltalk, but it does come up from time to time.

Need more help? There's a screencast for other topics like this which you may want to watch. Questions? Try the "Chat with James" Google gadget over in the sidebar.

Tags: ,

[st4u320-iPhone.m4v ( Size: 3329436 )]

posted by James Robertson

 Share Tweet This