Dependency Injection: Stop Creating Collaborators Inside
Dependency injection means a class receives the objects it works with from outside instead of creating them itself. It lets the same class run with different collaborators in one program without editing it. These lessons refactor a bike rental return desk that builds its own rate card and receipt printer.
Pick your language
When to use it
One class must work with different collaborators or settings in the same program, such as two branches, two currencies, or a fixed clock in a check.
The class has one setup of the collaborator that no caller will ever change, or the collaborator is a plain list it fills. Passing it in then only moves the creation outward.
A constructor that creates configured objects with values written inside it, or one that takes a flag only to choose which objects to create.