DEV Community

Discussion on: Explain Dependency Injection (DI) like I am five.

Collapse
 
derekjhopper profile image
Derek Hopper

I find code examples best for illustrating, so I'll share an example and try to explain. This is valid Ruby code, but will hopefully read more like pseudo code.

Without dependency injection:

class Teacher
  def grade(title, content)
    Paper.new(title, content).grade
  end
end
  • Anytime you want to grade a new type of paper, you need to update Teacher.
  • If the arguments of Paper change, you need to update Teacher.
  • Basically, the Teacher class has many reasons to change.

With dependency injection:

class Teacher
  def grade(paper)
    paper.grade
  end
end

teacher.grade(Paper.new(title, content))
teacher.grade(BookReport.new(book, title, content))
teacher.grade(ComputerScienceEssay.new(content))
  • By default, you can grade many types of papers. As long as any new Paper has a grade method, the Teacher can handle it.
  • The Teacher class has fewer reasons to change now.

I realize this isn't a simple explanation yet, so I'll try to simplify. Dependency injection gives you a Teacher that knows how to grade any paper you assigned to students in the past and any paper you might assign in the future. Without it, the Teacher needs to go back to school whenever a new paper is assigned.