Closures, Visitors, and Hedgehogs
By Darcy-Oracle on May 14, 2007
It has been said that there are foxes and there are hedgehogs and "the fox knows many tricks, but the hedgehog knows one great trick." The one great trick of computer science is adding a level of indirection in the right place. There is an interesting similarity between the level of indirection added by the visitor pattern and by closures.
when used on a type hierarchy allows arbitrary operations to be added
independently by third parties after the hierarchy is made, at the
upfront cost of an
accept method and the visitor
Closures when supported in a
programming language allow control APIs to be added
independently of evolving the language, at the upfront cost of
supporting closures in the language. A control API would be something
similar to the enhanced for loop in JDK 5 operating on Collections
implemented as a library method in
java.util rather than
a language change.
With both visitors and closures, the construct may be unfamiliar when first seen, but the utility of these patterns make them well worth learning. The extensibility afforded by visitors and closures creates much more scalable environments by allowing functionality to be added without the need for coordination from a single authority, either the type hierarchy or language maintainer.