Reputation: 960
As a new user to programming in general, I'm trying to understand dependency injection.
Is there ever a time where it's appropriate to instantiate an object within another class or is the idea that all objects will be instantiated in Main?
Upvotes: 1
Views: 73
Reputation:
Yes, there are plenty of times where it's appropriate to instantiate objects inside other objects. Dependency injection is for dependencies, not for data objects and such.
But even in the case of "dependencies", there are cases where it's fine to create them inside another object. If the objects you're creating are logically part of the object creating them, then dependency injection may be overkill. Sometimes I'll organize code into multiple classes without intending the smaller pieces to be standalone in any way. In those cases I may just new
them inside something else.
But it's a judgment call. Even in such cases it may be nice to be able to unit test the smaller bits in isolation, for example.
Upvotes: 1