How to explain dependency injection to a 5-year-old? [closed]
Asked Answered
C

5

208

What is a good way to explain dependency injection?

I found several tutorials on Google, but none of them that would assume the reader is just a Java beginner. How would you explain this to a novice?

Cyd answered 28/10, 2009 at 17:48 Comment(9)
Sounds like that kid's in for a hard life...Tractate
Start with "Once upon a time ....."Lcm
Are we talking about a Java beginner or a literal five year old?Chenay
With analogies, patience, and shock therapyHaggadist
# Dependency injection # don' depend on the age of learner, It is same for every onePotion
Rakesh: JavaOne 2009 introductory video is built on the premise that even a 13 year can be a Java developer because Java is "everywhere" and "easy".Stripy
May be this article would help any new bee. kevinwilliampang.com/2009/11/07/…Southerland
I sure hope when you said "explain to a 5 year old" that you simply meant beginners.Grumous
As a note, this question is the subject of the following Meta discussion: meta.#337519Grilled
C
788

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.

Corporative answered 28/10, 2009 at 17:56 Comment(0)
S
92

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 within 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 especially 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.

Shelled answered 28/10, 2009 at 18:29 Comment(2)
Or: Dependency injections is when you have something setting the dependencies for you. This something is usually a framework. :)Shelled
a very smart one indeed.Shelled
P
24

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.

Pender answered 28/10, 2009 at 18:50 Comment(0)
L
10

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.

Larainelarboard answered 28/10, 2009 at 17:59 Comment(0)
B
7

When you get given a new Nintendo, you can just use the buttons and touch screen to play games.

But at the Nintendo factory, they need to know how to put one together.

When the smart people at the factory bring out a Nintendo DS, it will be different inside, but you will still know how to use it.

Bonnes answered 7/7, 2011 at 3:7 Comment(1)
This sounds more like a description of interfaces or polymorphism, but I give you credit for actually being comprehensible for a 5-year old.Corriveau

© 2022 - 2024 — McMap. All rights reserved.