Friday, June 04, 2010

Delicious wraps

Ever needed to perform some computation in another thread, and the return the result. Typically what you do is you create a Runnable, where you perform this computation, run it in the separate thread, wait for it to complete and then somehow get the value out of that runnable and return it to the caller.

In SWT, this type of pattern is quite common when you need access to some widget values from outside of Display thread:

Nothing really revolutionary in this piece of code — Since the only safe way to ask text of the widget is to ask it from the display thread, I am invoking syncExec on the text widget's display.

To access the text field itself from the anonymous runnable, I have to declare it final. Also, to be able to return the value I need to write it to a local variable retValue, which needs to be declared final as well so that I could reference it from the inner anonymous class run method body.

In order to be able to write to the retVal, I also need to declare this final variable to be an array with length 1 and use first element of the array to hold the value.

This is a bit cumbersome but quite common pattern in Java brought on by a combination of weird scoping access rules and lack of true closures in the language.

In itself, it is not all to difficult to master, but to me it has always felt somehow ... hackish and unclean. It is not an array that I want in retValue, it is the value itself. Not to mention that if I need the computation to return an array of items, I always seem to forget how exactly should I initialize the 2 dimensional array...

Enter the Wrap — a delicios form of fast food, that when prepared with fresh vegetables and just the right amount of white and well seasoned meat, will quickly sate my hunger and still make feel better about myself than when I have a burger instead...

Just take a look at this extremely simple and almost naive piece of code. It does not do almost anything except allow access to a internally stored variable. It is just a light wrapping around a tasty filling that can make your life just so much easier.

Just consider the following snippet:

This feels just so much cleaner now than hacking around with arrays that I already feel much better just by looking at it :)