core error

Dependency Injection

Posted on: 12/07/2011

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).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


    • 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

    %d bloggers like this: