A functor, also called function object is an object that encapsulates a function or an expression. It is commonly required for functional programming style. It can enable higher order functions and internal iterators. The C++ Standard Template Library (STL) uses functors quite frequently and helps in creating them. The Wikipedia article has more information about functors for other languages.
I recently came across some libraries in Java too. jga, a functors library, has matured upto 0.8 (via Elliotte Rusty Harold), the Apache Commons Functor is in works and there is also the the Mango library.
There are some extensions that enable functional programming, but these libraries make it easier for functors. I admit that it took me some time to realise benefits of using functors. It is not something that must be used, or that is the only solution. There are other ways too. However, it can be one of the cleanest ways. I think it requires a different way of thinking about the design, which takes more time to mould rather than understanding functors.
One of the places where functors can help a lot is providing extension points or hooks for API. A lot of times APIs suffer because they do not offer enough points for the user to extend or customize. A common example is a sorting function. Instead of imposing the compare utility, it can let the user provide a custom compare utility. They can be done in other ways, but the functional programming way is cleaner.



February 5th, 2008 at 6:45 am
I have been using Apache Commons Functor extensively for sometime. The ChainedClosure/ChainedTransformer are whoever sent. It makes programming chain-of-responsibility just such a breeze and clean and precise. It is also very make it very easy to change code. Truely plug-and-play. Predicate/Closure|Transformer allow the plug-and-play feel really shine through. And the predicates allow for regrassion testing on conditionals; that can’t be beat!