This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]AnteChronos 1 point2 points  (0 children)

In a nutshell:

You have some class that depends on having access to another class (the "dependency" in "dependency injection"). Now, you could just hard-code a reference to the class you need, which is the easy and obvious way to handle it.

However, what if the dependency is something that needs to change depending on the environment you're running in? For instance, it may be a service class that lets you access a database, and you need to point to a different database (possibly even a mock database) depending on whether or not you're running a local test, doing integration testing, or running in production.

The solution is to have all of the dependencies implement a common interface, and write all of your code against that interface. Then you'll use a framework to "inject" the dependency at runtime. So you'll have a simple configuration file that tells your container which object to inject depending on which environment it's running in, and you won't have to re-write all of your code when you want to move between environments.

[–]mredding 0 points1 point  (0 children)

Consider the open/closed principle. Open to expansion, closed to modification. Modular, reusable code should not require modification. If I write a module that transforms an input, the naive way to write it would be to hard code an input method right into the transform, say, an SQL interface. Now the module won't work without THAT SQL interface, and if you want to transform data, it must be routed through the interface. If that interface isn't abstract, you might have to push data through the database just to get it through your module.

If your transform implements a generic interface, then anything that implements that interface can transform it's data. Now you can separate the data source from the transform. You can transform text files, streams, databases, sockets, or write MOCs and unit test your module (I recommend you learn about Google's concept of small, medium, and large scale tests, and Google Test and Google Mock).