Codele / Advanced programming
Dependency injection
A lamp with a socket lets you swap the bulb. A lamp with the bulb welded in does not. Objects work the same way: hand them what they need instead of letting them build it.
- A dependency is something an object needs to do its job. The Notifier needs a sender.
- Dependency injection means the thing is handed in from outside, usually through the constructor, instead of being built inside. The object then works with anything that keeps the same promise (an interface).
- Injection makes testing easy: hand in a fake that records messages instead of a real sender, so a test never emails a real person.
- Python and JavaScript have no interface keyword: any object with a send method fits the socket. Java, C# and Go declare the promise, and C++ uses an abstract class. Big frameworks inject for you, but the idea is exactly this one line.
Loading the playable lesson…