Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does anyone have a good analogy for dependency injection? [closed]

I have read a lot of articles on Dependency Injection as well as watched a lot of videos, but I still can't get my head around it. Does anyone have a good analogy to explain it?

I watched the first part of the Autumn of Agile screencast and still was a little confused.

like image 509
Xaisoft Avatar asked Sep 10 '25 05:09

Xaisoft


1 Answers

Analogy? I'll give it a whack... Your CD Player stereo is useless without a CD with music on it... (It's dependent on the CD). If they built CD Players with the CD already in it, it would get boring very quickly...

So they build them so you can "inject" the CD, (on which it is dependent) into the player. That way you can inject a different one each time, and get "different" behavior (music) dependent on which one you inject.

The only requirement is that the CD must be compatible with the interface defined by the player. (You can't play a blue-ray disk in a 1992 CD player.)

like image 107
Charles Bretana Avatar answered Sep 13 '25 16:09

Charles Bretana