I remember reading an analogy (i can't find the source) referring to going to a hardware store to buy a hammer but being instead sold blueprints to to a factory that makes hammers.
There are advantages with DI that people cannot attribute in real life. In engineering, there are cases where the program expects a hammer, but you would like to see if it can make the same action with a screwdriver (say, for testing a new product that needs the same instructions but different pieces).
To use your analogy, the guy would then give you the blueprints to a factory that makes screwdrivers.
So it's useful to have that second indirection. People just think it's complicated because they don't have the experience to see the shortcomings of simply getting a hammer.
Having done a lot of programming in python and in functional programming langauges, I get rather confused by the crazy abundance of factories in code. Is there a good explination for what problems it solves that cant be solved easier in some other way? Is it more then a hack to get around not having first class functions? Because as I see it, if I want code that does an action with a hammer and a screwdriver, then it just takes a tool in the first place. I dont need a blueprint for a factory.
When you create something, you inherently know exactly what it is. When you use something, you use a general interface that lets you do any general actions you need to with it. And I get that dependancy injection lets you match up the two in in a more declarative and loose fitting way. And I see why sometimes it might be useful to have something stateful that lets you create other things. But it seems like the definitions used is Spring or whatnot go way beyond that, and I am not sure how those factories fit in to this.
15
u/bryanedds Apr 23 '14
"And a factory in Chicago that makes miniature models of factories."