This week we talk about recognizing dependencies, isolating dependencies, and managing dependency direction.
To collaborate, an object must know something about others. Knowing creates a dependency. If not managed carefully, these dependencies will strangle your application
An object has a dependency when it knows:
Gear
expects a class named Wheel
to existself
.
Gear
expects a Wheel
instance to respond to diameter
Gear
knows that Wheel.new
requires a rim
and a tire
Gear
knows the first argument to Wheel.new
should be rim
and the second should be tire
see 1_inject_dependencies.rb
Wheel
class changes, the gear_inches
method must also changegear_inches
is explicitly saying that it is only willing to calculate gear inches for instances of Wheel
Gear
will only collaborate with any other kind of object even if that object has a diameter and uses gears!It's is not the class of the object that's important, it's the message you plan to send to it.
Gear
needs access to an object that can respond to diameter
- a duck typeWheel
instance outside of the classsee 2_isolate_dependencies.rb
Isolate Instance Creation
Wheel.new
from gear_inches
and into Gear
's initialize
methodWheel
into its own wheel
methodIsolate Vulnerable External Messages
gear_inches
depends on Gear
responding to wheel
and wheel
responding to diameter
diameter
method to hold wheel.diameter
, we remove the dependency within gear_inches
see 3_remove_arg_orer_dependencies.rb
Use Hashes for Initialization Arguments
initialize
method must be passed in the correct order. we can pass an object instead to remove this dependencyExplicitly Define Defaults
fetch
method to set defaults when using hashes in our initialize
methodfetch
expects the key you're fetching to be in the hash and supplies several options for handling missing keysfetch
will only set the default if the key is not found in the hashGear
depending on Wheel
or diameter
- but the code could have easily been written so that Wheel
depends on Gear
or ratio
Depend on things that change less often
John’s pick - Pick Krisp -https://krisp.ai