Back in December, I had a post about why closures are useful
. In particular, I mentioned what I called the "generalized Template Method" pattern as a benefit: basically, you have a function where, when the user calls it, you want them to be able to change its behavior in some way.
I was short of practical examples, but today I came across one. I've got a
function that behaves identically for each object it is called on. Basically, it figures out what properties the object has that should be listed, and creates a table that lists them for some query result set. Normally, this just outputs the variable's value on a cell with a white background. The slight change in this case was that depending on the value, the list should set a background color to one particular cell.
Being that I've been burned a lot in the past by not following the DRY
principles, I'm quite fanatacal about following them nowadays. So when I needed the
function to behave a bit differently for this one type of object, I didn't want to replicate the entire list function -- I just wanted to add a bit of logic in the middle. That's where closures enter the picture.
I decided I'd create a function,
onOutputOf(column="column that special stuff needs to be done to", run="function, or code")
. So, instead of outputting the value of the cell, the list now knows to run the code provided in the
And now, some really complex code doesn't need to be replicated elsewhere. Isn't that sweet?
Hey! Why don't you make your life easier and subscribe to the full post
or short blurb RSS feed? I'm so confident you'll love my smelly pasta plate
wisdom that I'm offering a no-strings-attached, lifetime money back guarantee!
Leave a comment
Is posting your code (or a reasonable excerpt) a possibility? I've been looking for a good, practical example of a useful closure. I'd love to see a little more context if you can post it.
Posted by Rob Wilkerson
on Apr 26, 2007 at 12:07 PM UTC - 5 hrs
Leave a comment
Rob, actually I thought that might be a fairly useless post without an example. =) I think the actual code that I used this on would be too complex to be a good example (too much dynamic stuff to follow). However, it will be made public anyway, so I have no qualms in posting it for those sorts of reasons.
I'll come up with a stripped down example that should make it easier to follow. I don't know if I can get to it today (though I'll try), but I'll post it here so you should see it in an email (assuming you've subscribed) when I do (no later than this weekend).
And thanks for the suggestion!
Posted by Sam
on Apr 26, 2007 at 12:20 PM UTC - 5 hrs