Inject Dependencies

Injecting dependencies allows you to keep dependency resolutions close to the logic that affects them. It can prevent sub-dependencies from leaking throughout the code base, and it makes it easier to change the behavior of related components without modifying those components’ classes.

Although many people think of dependency injection frameworks and XML when they hear “dependency injection,” injecting a dependency is usually as simple as passing it as a parameter.

  1. Move the dependency decision to a higher level component.
  2. Pass the dependency as a parameter to the lower level component.
  3. Remove any sub-dependencies from the lower level component.

Injecting dependencies is the simplest way to invert control.

Drawbacks

It’s important to remember that the further you move a dependency’s resolution from its use, the harder it is to figure out what’s actually being used in lower level components.

Việc sử dụng DI làm ta khó để biết được thực sự object của class nào đang được gọi (ở low level)

Ví dụ

# app/models/question.rb
def summary_using(summarizer)
	value = summarizer.summarize(self) 
	Summary.new(title, value)
end

Ở đây, mình không biết được summarize là object của class nào, Summarizer::Breakdown, Summarizer::MostRecent, hay Summarizer::UserAnswer