Your PetManager class is responsible for creating and configuring the database, then uses that connection to save a pet record. With dependency injection, the key idea is that the dependency, which is the database connection in this case, can be passed in to the PetManager class from outside (usually as an interface). So it would look like this:
This makes it easier to unit test your PetManager class, since you can pass a test-only version of DbConnection. Also, if your application is running in a container of some kind, you can configure the database connection properties in the container, and then let the container wire up the database connection for you at run time. This gives you additional flexibility for setting up these kinds of external dependencies, which can also help with scalability and performance.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
A simple concrete example (using a vaguely Java/C# pseudocode): You want to save some data to a database. You can do something like this:
Your
PetManager
class is responsible for creating and configuring the database, then uses that connection to save a pet record. With dependency injection, the key idea is that the dependency, which is the database connection in this case, can be passed in to thePetManager
class from outside (usually as an interface). So it would look like this:This makes it easier to unit test your
PetManager
class, since you can pass a test-only version ofDbConnection
. Also, if your application is running in a container of some kind, you can configure the database connection properties in the container, and then let the container wire up the database connection for you at run time. This gives you additional flexibility for setting up these kinds of external dependencies, which can also help with scalability and performance.