Tuesday, January 18, 2011

Multiple Return Values in Smalltalk

In the comments of my "Two-Sided Commit" post, I referred to a technique I heard about from my friend Anthony Lander.  I thought I'd write that up explicitly.

Sometimes, you'd really like a method to return multiple values. Suppose, for example, we have a Color object that stores its value as integers for Red, Green and Blue.  We may want to compute the Hue, Saturation and Value of the color.  If we had individual methods for hue, saturation and value, we'd have to perform the calculation three times.  Alternatively, we could write a method for the object called asHSV which returns the hue, saturation and value in an Array.  Arrays, though, are messy to deal with because the values are indexed by an integer - you can't use the names  hue, saturation, and value. We could also create an object for an HSV representation of the color but that introduces a lot of complexity. The HSV color should work interchangeably with an RGB color and that amount of work may not be justified.

Rather than have multiple return values (or returning an array of values), we can use a three-parameter block and name the parameters:

    aColor asHSVDo: [:hue :saturation :value | ... ]

Now, the asHSVDo: method can perform the conversion once and run the block with the calculated values.  We get to use nice names for the variables and we don't create extra objects we don't need.

Sometimes, this turns out to be a nice alternative when you think you need multiple return values.

No comments:

Post a Comment