Chapter 4. Functors
Introduction
The American Heritage Dictionary defines a
functor
as “one that performs an operation or a
function,” and, in the context of programming, a
functor is an object that encapsulates “functional
logic”—a functional object. So with a
definition as abstract as “something that does
stuff,” you won’t find a lot of
satisfying, concise explanations of what a functor can do; in the
abstract, anything that performs an operation or function could be
considered a functor, and the process of drawing divisions between
what should and should not be implemented with functors becomes a
matter of personal preference. I’m not going to
attempt to give a well-polished, textbook definition of a functor;
this chapter simply demonstrates the set of basic functors from
Commons Collections. Functors are less of an impressive new
technology and are more of an approach to programming. Even if you
are unfamiliar with the term, you’ve likely used
functors without realizing it; two functors in common usage are
Comparator and Iterator.
Both Comparator and Iterator
serve to isolate an algorithm; Comparator
encapsulates logic to compare two objects, and
Iterator encapsulates logic used to iterate over a
collection of objects. Functors often lead to more code reuse and a
cleaner design because functional logic can be abstracted and
extracted out of logic dealing with a specific data structure. For
example, to compare two Person beans, you could
make the Person class implement
Comparable ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access