Many times you will want
to ???patch??? a feature onto an existing function without disturbing that function??™s
code. Your addition may not be directly related to the function??™s original purpose: it
may add authentication, logging, or some other important cross-cutting concern.
We will examine several approaches to the problem of cross-cutting concerns, and
explain the one (method chaining) that has acquired the most momentum in the
Ruby and Rails communities.
Subclassing
In traditional object-oriented programming, a class can be extended by inheriting
from it and changing its data or behavior. This paradigm works for many purposes,
but it has drawbacks:
??? The changes you want to make may be small, in which case setting up a new
class may be overly complex. Each new class in an inheritance hierarchy adds to
the mental overhead required to understand the code.
??? You may need to make a series of related changes to several otherwise-unrelated
classes. Subclassing each one individually would be overkill and would separate
functionality that should be kept together.
??? The class may already be in use throughout an application, and you want to
change its behavior globally.
??? You may want to add or remove a feature at runtime, and have it take effect globally.
(We will explore this technique with a full example later in the chapter.)
In more traditional object-oriented languages, these features would require complex
code.
Pages:
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64