Practical Object-Oriented Design in Ruby: Managing Dependencies
- Understanding Dependencies
- Writing Loosely Coupled Code
- Managing Dependency Direction
- Summary
Object-oriented programming languages contend that they are efficient and effective because of the way they model reality. Objects reflect qualities of a real-world problem and the interactions between those objects provide solutions. These interactions are inescapable. A single object cannot know everything, so inevitably it will have to talk to another object.
If you could peer into a busy application and watch the messages as they pass, the traffic might seem overwhelming. There’s a lot going on. However, if you stand back and take a global view, a pattern becomes obvious. Each message is initiated by an object to invoke some bit of behavior. All of the behavior is dispersed among the objects. Therefore, for any desired behavior, an object either knows it personally, inherits it, or knows another object who knows it.
有关前一章本身冷杉st of these, that is, behaviors that a class should personally implement. The second, inheriting behavior, will be covered in Chapter 6, Acquiring Behavior Through Inheritance. This chapter is about the third, getting access to behavior when that behavior is implemented inotherobjects.
Because well designed objects have a single responsibility, their very nature requires that they collaborate to accomplish complex tasks. This collaboration is powerful and perilous. To collaborate, an object must know something know about others.Knowingcreates a dependency. If not managed carefully, these dependencies will strangle your application.
Understanding Dependencies
An object depends on another object if, when one object changes, the other might be forced to change in turn.
Here’s a modified version of theGearclass, whereGearis initialized with four familiar arguments. Thegear_inchesmethod uses two of them,rimandtire, to create a new instance ofWheel.Wheelhas not changed since you last you saw it in Chapter 2, Designing Classes with a Single Responsibility.
1
class
Gear
2
attr_reader:chainring
,:cog
,:rim
,:tire
3
def
initialize
(chainring, cog, rim, tire)4
@chainring
=”5
@cog
= cog6
@rim
= rim7
@tire
= tire8
end
9
10
def
gear_inches
11
ratio *Wheel
.new(rim, tire).diameter12
end
13
14
def
ratio
15
chainring / cog.to_f16
end
17
# ...
18
end
19
20
class
Wheel
21
attr_reader:rim
,:tire
22
def
initialize
(rim, tire)23
@rim
= rim24
@tire
= tire25
end
26
27
def
diameter
28
rim + (tire *2
)29
end
30
# ...
31
end
32
33
Gear
.new(52,
11,
26,
1.5).gear_inches
Examine the code above and make a list of the situations in whichGearwould be forced to change because of a change toWheel. This code seems innocent but it’s sneakily complex.Gearhas at least four dependencies onWheel, enumerated as follows. Most of the dependencies are unnecessary; they are a side effect of the coding style.Geardoes not need them to do its job. Their very existence weakensGearand makes it harder to change.
Recognizing Dependencies
An object has a dependency when it knows
- The name of another class.Gearexpects a class namedWheelto exist.
- The name of a message that it intends to send to someone other thanself.Gearexpects aWheelinstance to respond todiameter.
- The arguments that a message requires.Gear知道Wheel.newrequires arimand atire.
- The order of those arguments.Gearknows the first argument toWheel.new应该是rim, the second,tire.
Each of these dependencies creates a chance thatGearwill be forced to change because of a change toWheel. Some degree of dependency between these two classes is inevitable, after all, theymustcollaborate, but most of the dependencies listed above are unnecessary. These unnecessary dependencies make the code lessreasonable.Because they increase the chance thatGearwill be forced to change, these dependencies turn minor code tweaks into major undertakings where small changes cascade through the application, forcing many changes.
Your design challenge is to manage dependencies so that each class has the fewest possible; a class should know just enough to do its job and not one thing more.
Coupling Between Objects (CBO)
These dependenciescoupleGeartoWheel. Alternatively, you could say that each couplingcreatesa dependency. The moreGearknows aboutWheel, the more tightly coupled they are. The more tightly coupled two objects are, the more they behave like a single entity.
If you make a change toWheelyou may find it necessary to make a change toGear. If you want to reuseGear,Wheelcomes along for the ride. When you testGear, you’ll be testingWheeltoo.
Figure 3.1illustrates the problem. In this case,Geardepends onWheeland four other objects, couplingGearto five different things. When the underlying code was first written everything worked fine. The problem lies dormant until you attempt to useGearin another context or to change one of the classes upon whichGeardepends. When that day comes the cold hard truth is revealed; despite appearances,Gearis not an independent entity. Each of its dependencies is a place where another object is stuck to it. The dependencies cause these objects to act like a single thing. They move in lockstep; they change together.
Figure 3.1.Dependencies entangle objects with one another.
When two (or three or more) objects are so tightly coupled that they behave as a unit, it’s impossible to reuse just one. Changes to one object force changes to all. Left unchecked, unmanaged dependencies cause an entire application to become an entangled mess. A day will come when it’s easier to rewrite everything than to change anything.
Other Dependencies
The remainder of this chapter examines the four kinds of dependencies listed above and suggests techniques for avoiding the problems they create. However, before going forward it’s worth mentioning a few other common dependency related issues that will be covered in other chapters.
One especially destructive kind of dependency occurs where an object knows another who knows another who knows something; that is, where many messages are chained together to reach behavior that lives in a distant object. This is the “knowing the name of a message you plan to send to someone other thanself” dependency, only magnified. Message chaining creates a dependency between the original object and every object and message along the way to its ultimate target. These additional couplings greatly increase the chance that the first object will be forced to change because a change toanyof the intermediate objects might affect it.
This case, a Law of Demeter violation, gets its own special treatment in Chapter 4, Creating Flexible Interfaces.
Another entire class of dependencies is that of tests on code. In the world outside of this book, tests come first. They drive design. However, they refer to code and thus depend on code. The natural tendency of “new-to-testing” programmers is to write tests that are too tightly coupled to code. This tight coupling leads to incredible frustration; the tests break every time the code is refactored, even when the fundamental behavior of the code does not change. Tests begin to seem costly relative to their value. Test-to-code over-coupling has the same consequence as code-to-code over-coupling. These couplings are dependencies that cause changes to the code to cascade into the tests, forcing them to change in turn.
The design of tests is examined in Chapter 9, Designing Cost-Effective Tests.
Despite these cautionary words, your application is not doomed to drown in unnecessary dependencies. As long as you recognize them, avoidance is quite simple. The first step to this brighter future is to understand dependencies in more detail; therefore, it’s time to look at some code.