Categories
Programming

Closures

I had a real “aha moment” today while coding some javascript. Let me first start this post with a quote:

The venerable master Qc Na was walking with his student, Anton.  Hoping to
prompt the master into a discussion, Anton said "Master, I have heard that
objects are a very good thing - is this true?"  Qc Na looked pityingly at
his student and replied, "Foolish pupil - objects are merely a poor man's
closures."

  Chastised, Anton took his leave from his master and returned to his cell,
intent on studying closures.  He carefully read the entire "Lambda: The
Ultimate..." series of papers and its cousins, and implemented a small
Scheme interpreter with a closure-based object system.  He learned much, and
looked forward to informing his master of his progress.

  On his next walk with Qc Na, Anton attempted to impress his master by
saying "Master, I have diligently studied the matter, and now understand
that objects are truly a poor man's closures."  Qc Na responded by hitting
Anton with his stick, saying "When will you learn? Closures are a poor man's
object."  At that moment, Anton became enlightened.

When I first read this some time ago I thought I understood it. I did not I now understand and my aha moment today proved that. I have written way too little pure functional programming to really appreciate and use the power of closures. Not to say that objects are useless. That’s exactly the point of the quoted text. Just that the ability to define closures inside closures inside closures is a really really powerful concept. The idea is that sometimes code gets repeated in a function inside a class. Typically you pull that into a helper function and stick it on the class, but sometimes the function is so specialized that it has no livelihood in the class. Secondly the ability to bind local objects to closures, and use those closures as state is another aspect of closures that is immensely powerful.