Wednesday, February 15, 2006

Dependency Injection

In order to reduce the amount of coupling between components, most programmers follow the "Program to an interface, not an implementation" principle, which is the first principle defined in the GoF Design patterns book. In doing so, you will be able to change the implementation without affecting the client programmed to the published interface. One more advantage of doing so is that the implementation class can be defined at runtime. This is done through dependency injection. For example

public class Client {
private MyInterface var;
public Client(MyInterface var1) {
var = var1;
// Instead of var = new MyImplementation();

Now without any reference to the actual implementation, we can write the client program. The method described above is also known as Constructor Injection (which is a variant of Dependency Injection). The other variant is Setter Injection, in which a setter is provided to set the value of the dependency (MyImplementation in the above example). Martin fowler has nice introduction to depency injection on his website.

No comments:

Post a Comment

Popular Posts