views:

1097

answers:

8

Hello there,

Could anybody point out a good dependency injection tutorial? I found a ton on Google but none of them that would assume the reader is a just Java beginner.

Thanks!

+3  A: 

This explanation is pretty simple:

http://codeutopia.net/blog/2008/06/21/dependency-injection-or-how-to-make-simple-concepts-sound-difficult/

As a side note you might want to take a look at this book:

http://www.amazon.co.uk/Head-First-Design-Patterns-Freeman/dp/0596007124/ref=sr_1_1?ie=UTF8&s=books&qid=1256752688&sr=1-1

It has been specifically designed by O'Reilly to be easy to understand and take in.

lexx
I'm a newbie and I really found the Head First book easy to deal with. I had just a bit of Java experience then.
PRINCESS FLUFF
A: 

For a five year old? For an adult Java beginner, try the metaphor of pregnancy using artificial insemination to bypass the messy details of sexual intercourse.

[p.s.]

To understand dependency injection does require a degree of sophistication, given that it is addressing an architectural issue that is not readily apparent to the novice.

The metaphor cited was not flippant. You require a certain benefit without entanglements.

-1: It's a perfectly valid question.
TrueWill
It's a really bad metaphor. Who would want to skip the best part to get to the hard to support and expensive part?
Carlos
Yikes, I'm not even going to ask you about Inversion of Control
Mike Sickler
@Mike S: LOL. But if you're curious ... http://en.wikipedia.org/wiki/Power_exchange_(BDSM)
@alphazero No! My eyes!
Mike Sickler
A: 

http://java.dzone.com/articles/dependency-injection-an-introd has a pretty good introduction with examples in Java using an Automated Teller Machine.

Ezweb
+68  A: 

I give you dependency injection for five year olds.

When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might even be looking for something we don't even have or which has expired.

What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat.

John Munsch
+1 -- very nice
Bob
This answer is going places.
Michael Myers
Absolutely brilliant. +1
Adam Maras
ceiling cat is watching you overflow stack
Longpoke
+1  A: 

I don't know of any simplified tutorials, but I can give you an almost 25 250-words-or-less version:

With dependency injection an object doesn't configure its own components based on things it already knows, rather the object is configured by higher level logic, and then it calls components that it didn't have built-in foreknowledge of. The idea is to make the object more of a component and less of an application, relocating configuration tasks at a higher level. This makes the object more likely to be useful in the future or with a different configuration.

It's better for testing, it's better when it comes time to revise the application. A typical implementation puts the configuration in XML and uses a framework to dynamically load classes.

DigitalRoss
+2  A: 

What about this?

If you have a class Employee and this employee has an Address you can have the Employee class defined as follows:

class Employee {
    private Address address;

    // constructor 
    public Employee( Address newAddress ) {
        this.address = newAddress;
    }

    public Address getAddress() {
    return this.address;
    }
    public void setAddress( Address newAddress ) {
        this.address = newAddress;
    }
}

Everything looks fine so far.

This code shows a HAS-A relationship between the employee and his address, that's fine.

Now, this HAS-A relationship created a dependency between them. The problem comes when with the constructor.

Each time you want to create an Employee instance you need an Address instance:

 Address someAddress = ....
 Employee oscar = new Employee( someAddress );

Working this way becomes problematic specially when you want to perform unit testing.

The main problem comes when you need to test one particular object, you need to create an instance of other object, and most likely you need to create an instance of yet other object to do that. The chain may become unmanageable.

To avoid this, you could change the constructor like this:

  public Employee(){
  }

Using a no args constructor.

Then you can set the address when ever you want:

 Address someAddress = ....
 Employee oscar = new Employee();
 oscar.setAddress( someAddress );

Now, this may be a drag, if you have several attributes or if the objects are hard to create.

Yet, think about this, let's say, you add the Department attribute:

  class Employee {
      private Address address;
      private Department department;

  ....

If you have 300 employees, and all of them need to have the same department, and plus that same department has to be shared between some other objects ( like the company list of departments, or the roles each department have etc ) then you'll have a hard time with the visibility of the Department object and to share it through all the network of objects.

What the Dependency Injection is all about it to help you to, well, "inject" these dependencies in your code. Most of the frameworks allow you to do this by specifying in an external file, what object is to be injected.

Assume a properties file for a fictitious dependency injector:

  #mock employee
  employee.address = MockAddress.class
  employee.department = MockDepartment.class

  #production setup 
  employee.address = RealAddress.class
  employee.department = RealDepartment.class

You'll define what to inject for a given scenario.

What the Dependency Injector framework will do is to set the correct objects for you, so you don't have to code setAddress or setDepartment. This would be done either by reflection or by code generation or other techniques.

So, the next time you need to test the Employee class you may inject mock Address and Departments objects without having to code all the set/get for all your test. Even better, you can inject real Address and Department objects in production code, and still have the confidence your code works as tested.

That's pretty much about it.

Still I don't think this explanation is suitable for a 5 yr old as you requested.

I hope you still find it useful.

OscarRyz
Or: Dependency injections is when you have *something* setting the dependencies for you. This something is usually a framework. :)
OscarRyz
Is this for 5 yr old kid?
Rakesh Juyal
a very smart one indeed.
OscarRyz
Thanks, that's useful for me!
PRINCESS FLUFF
Nice explanation!
bobjink
A: 

Hollywood principle, don't call us we'll call you.

lemotdit
That would be Inversion Of Control (IoC), not Dependency Injection.
Stefano Ricciardi
I thought they were synonyms :(
PRINCESS FLUFF
+1  A: 

When writing a class, it's natural for it to make use of other objects. You may have a database connection, for example, or some other service that you use. These other objects (or services) are dependencies. The simplest way to write the code is simply to create and use those other objects. But this means your object has an inflexible relationship to those dependencies: no matter why you are invoking your object, it uses the same dependencies.

A more powerful technique is to be able to create your object and provide it with dependencies to use. So you might create a database connection to use, then hand it to your object. This way, you can create your object with different dependencies at different times, making your object more flexible. This is dependency injection, where you "inject" the dependencies into the object.

BTW: In the modern presentation style of using flickr photos to illustrate concepts, this could be illustrated with an addict shooting themselves up with drugs. Oh, wait, that's injection dependency... OK, sorry, bad joke.

Ned Batchelder
its not a bad joke :D
Sdry