25. Dependency Inversion Principle
A. High-level modules should not depend on low-level
modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should
depend on abstractions.
25/103
65. Benefits
• You don't need to think about building objects
• All code is built on the same principles
• It's far easier to write testable code
• You, most likely, will write functional-ish code
• Speeds up tests in a natural way
65/103
69. dry-system
• Extends $LOAD_PATH
• Uses require to load files
• Registers dependencies automatically
• Builds dependencies using name conventions
• Can split an application into sub-apps
69/103
70. dry-system
class Application < Dry::System::Container
configure do |config|
config.root = Pathname('./app')
end
end
70/103
71. dry-system
class Application < Dry::System::Container
configure do |config|
config.root = Pathname('./app')
config.auto_register = 'lib'
end
load_paths!('lib')
end
71/103
95. Cons:
• Can't be memoized
• Can violate boundaries
Pros:
• Reduces code duplcation
95/103
96. Cons:
• Can't be memoized
• Can violate boundaries
Pros:
• Reduces code duplcation
• Simplifies context sharing
96/103
97. Cons:
• Can't be memoized
• Can violate boundaries
Pros:
• Reduces code duplcation (no need to pass arguments)
• Simplifies context sharing
• Kills global state
97/103
99. Recap
• DI is a way to implement the dependency inversion
principle
• This makes your code easier to test and write
• Can break an application into sub-apps
• Can remove the global state as a whole (100% FP)
• Can be done in Ruby in one evening
• Doesn't have any major disadvantages *
99/103
100. DI 101
• Replace hard dependencies with interfaces (plain Ruby)
• Put dependencies into a container (dry-container)
• Inject dependencies automatically (dry-auto_inject)
• Organize application code in modules (dry-system)
100/103
101. Caveats
• Don't put every single thing into a container
• Make dependencies pure (aka thread-safe)
• Keep interfaces simple
• Injecting a dozen of deps at once is bad, m'kay?
• Fear new abstractions
101/103