I'll Be Backend
Design patterns

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

Use it when

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.

Skip it when

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.

Spot it by

A constructor that creates configured objects with values written inside it, or one that takes a flag only to choose which objects to create.