Chapter 3 Flashcards
Dependencies
An object depends on another object if, when one object changes, the other might be forced to change in turn.
Dependency Injection
Using dependency injection to shape code relies on your ability to recognize that the responsibility for knowing the name of a class and the responsibility for knowing the name of a message to send to that class may belong in different objects.
Dependency Injection
Using dependency injection to shape code relies on your ability to recognize that the responsibility for knowing the name of a class and the responsibility for knowing the name of a message to send to that class may belong in different objects.
Use Hashes for Initialization Arguments.
class Gear attr_reader :chainring, :cog, :wheel def initialize(args) @chainring = args[:chainring] @cog = args[:cog] @wheel = args[:wheel] end end
Removes every dependency on argument order.
The key names in the hash furnish explicit documentation about the arguments.
Use Hashes for Initialization Arguments.
class Gear attr_reader :chainring, :cog, :wheel def initialize(args) @chainring = args[:chainring] @cog = args[:cog] @wheel = args[:wheel] end end
Removes every dependency on argument order.
The key names in the hash furnish explicit documentation about the arguments.
fetch
The fetch method expects the key you’re fetching to be in the hash and supplies several options for explicitly handling missing keys.
def initialize(args) @wheel = args.fetch(:wheel, 40) @cog = args.fetch(:cog, 1) end
Factory
An Object used to create other objects.
Summary
Dependency management is core to creating future-proof applications. Injecting dependencies creates loosely coupled objects that can be reused in novel ways. Isolating dependencies allows objects to quickly adapt to unexpected changes. Depending on abstractions decreases the likelihood of facing these changes.
The key to managing dependencies is to control their direction. The road to maintenance nirvana is paved with classes that depend on things that change less often than they do.