After listening to the Clean Code Talks, I came to understand that we should use factories to compose objects. So, for example, if a House
has a Door
and a Door
has a DoorKnob
, in HouseFactory
we create a new DoorKnob
and pass it to the constructor of Door
, and then pass that new Door
object to the constructor of House
.
But what about the class that uses the House
(say the class name is ABC
)? It will depend on the HouseFactory
, right? So do we pass the HouseFactory
in the constructor of ABC
? Won't we have to pass a whole lot of factories in the constructor that way?
Staying with the Door and DoorKnob example, you don't inject a factory - you inject the DooKnob itself:
No factories are in sight in this level.
House, on the other hand, depends on Door, but not on DoorKnob:
This keeps options open until at last you have to compose everything in the application's Composition Root:
You can use a DI Container to compose at this level, but you don't have to. No factories are involved.