core error

Archive for the ‘Design Patterns’ Category

What?

Dependency Injection is about avoiding the creation of member classes inside other classes. Any member class we need inside in another class can be provided through the constructor or a setter method.

Why?

Two reasons:

  1. Helps reducing the coupling between classes so we are protected against future changes in those classes
  2. Allows you to unitest MUCH easier. We can provide each class with mock-ups in a really simple way

How?

This class is tightly coupled to a repository class:

public class MyClass{
    private MyRepo _repo;

    public Cliente getCustomer(int id)
    {
         _repo    = new MyRepo();
         var customer = _repo.LookForCustomer(id);
         return customer;
    }
}

We can inject the repository and remove that dependency from the class itself:

public class MyClass{
    private iMyRepo _repo;

    public MyClass(iMyRepo repo){
         _repo = repo;
    }

    public Cliente getCustomer(int id)
    {
         var customer = _repo.LookForCustomer(id);
         return customer;
    }
}

By doing this, we removed the coupling from MyClass and moved it to a more changing class (like a factory).



    • Justin Cooney: Great comic, this made me laugh!
    • Justin Cooney: Interesting, I didn't know about the Google App Engine, I'm glad I found your article on it!

    Categories