OK, I've been meaning to blog about this for awhile. But, I just got around to it and since I was debugging some HttpUnitTest code involving Seaside...I thought, "What the HECK!" Anyway, so, what's worthy of blogging about Seaside that I haven't already. It's a cool little trick with Smalltalk's exception handling. First off, let me give you a little bit of background. When I learned Lisp, one thing that struck as being very cool was the notion of defining your own scope for variables. They don't have to conform to the boundaries of a method or a context. In fact, you can have them span several methods. While it is seldom needed, it is an excellent trick to have in your bag. I had been thinking for awhile that it would be a cool thing to have in Smalltalk. I thought immediately, I could have these dynamic variables defined in a block context and look up the stack when I needed their values. But, the code was messy. Well, one day I was looking at Seaside code and noticed that they use these "dynamic variables" for holding onto the current session in Seaside. But, he uses the plumbing already there in Smalltalk! He uses the exception handling framework! The code is so simple and I smacked myself on the head! BRILLIANCE! Here's the code taken from the Seaside source (I hope nobody minds)
- WADynamicVariable>>use: anObject during: aBlock
do: [:n | n resume: anObject]
^ self raiseSignal
Now, all you have to do is do something like the following code:
- WADynamicVariable use: 'poo' during: [self doSomeStuff]
Anytime, you want the value of your dynamic variable, all you need to do is:
- WADynamicVariable value
And it will return to you the value that is currently set in the stack for WADynamicVariable. Now, of course, you will want to create your subclass for your values so that it doesn't clash or you could have WADynamicVariable hold on to a dictionary of values and you access it via that (you could even use doesNotUnderstand to make variables easier to get to). Anyway, the code is simple and shows you what a little ingenuity in Smalltalk can do. There's a lot of cool things you can do with the exception handling framework in Smalltalk and use it in unexpected ways. This is just one of them.
Anyway, I thought it was a cool trick and a cool one to show off. I would like to thank the coders of Seaside for this idea. It's a good one!