The Function Object Pattern

K Thomas · 1997

The Function Object pattern can be regarded as a variation to the Command pattern that takes parameters and returns a result. The pattern describes how to build encapsulated components for behavior parameterization, function reuse, calculation on demand, representing “business-transactions”, and first-class behavior, e.g., protocol-, undo-, and persistence mechanisms. In contrast to Command, Function Object establishes a useful collaboration with iterators. We show in particular how to use generic function objects with iterators in order to allow multi-dispatching operations on heterogeneous data structures. Function Object belongs to the class of design patterns that describe how to compensate for missing language features. For instance, Convenience Methods [7] shows how to emulate default parameters and Visitor [5] is less needed in languages with multi-dispatch. Function Object describes how to achieve the benefits that Smalltalk programmers gain from blocks (and functional programmers gain from higher-order functions) in object-oriented languages without such a feature. Very similar to the Command pattern [5] Function Object objectifies behavior and thus opens up many useful applications (see section 2.4) which go even beyond the potential of Smalltalk blocks (see section 2.9.4). As Command and Strategy [5] Function Object defines behavior that is not tied to a particular data abstraction. So-called free functions usually do not occur during domain analysis. They resemble socalled design-objects [12], like iterator objects, and event handler. Technically commands and function objects can be called closures. A closure is a function that on creation is able to capture variables values from its environment. In case of Command the environment variables (e.g., the text for an editor command) are passed as constructor arguments. In addition, a function object accepts further arguments after creation from any client it was passed to and with all benefits of partial parameterization (see section 2.3). The following section not only explains a design technique but deliberately uses many examples to illustrate the various usages of Function Object. Section 3 then attempts to explain Function Object’s implications for software reuse by enumerating the abstract concepts involved.

Read the paper · More papers on PaperTik