Showing posts with label DependencyInjection. Show all posts
Showing posts with label DependencyInjection. Show all posts

Thursday, July 15, 2010

Dependency Injection and Unit Testing

In recent years, Dependency Injection may have buzzed into your ears quite often. You may already know that it has nothing to do with drug addiction, but with some cool object-oriented concept. You may also have heard of the Spring Framework, a so-called Dependency Injection container. You might be under the impression that Dependency Injection equals Spring. But no, Dependency Injection is a simple concept which can be used anywhere, without any Dependency Injection container, and especially useful in unit testing. In this article, we will see

  • what Dependency Injection is
  • how to make a class Dependency Injection friendly
  • why Dependency Injection can ease unit tests

Ladies and gentlemen, start your engine !

A simple car

Let's consider a simple example, using engines and cars. We'll leave classes and interfaces empty for clarity. A car has an engine, and we'd like that car to be equipped with JavaRanch's famous MooseEngine™.


We've got engines:
public interface Engine { } public class SlowEngine implements Engine { } public class FastEngine implements Engine { } public class MooseEngine implements Engine { } 
And we've got a car:
public class Car {  private MooseEngine engine; } 

This is a great car, but it cannot have any other kind of engine, although there are other brands available on the market. We say that the Car class is tightly coupled to the MooseEngine class. There's nothing wrong with it, the MooseEngine™ is great, but what happens if we finally decide to equip it with another engine ?

Programming with interfaces

You may have noticed that the MooseEngine™ was implementing the Engine interface. Other brands are also implementing the same interface. Let's think about it. When we designed our Car class, we thought that a "car" was equipped with an "engine". So let's rewrite the Car class to use the Engine interface instead:
public class Car {  private Engine engine; } 

Programming with interfaces is an important concept in Dependency Injection. I can already hear you screaming, "wait a minute! That's an interface you're using here, where is the concrete class? Where do you set it? I want my MooseEngine™ in my car". We could set it the following way:
public class Car {  private Engine engine = new MooseEngine(); } 
But would that be useful ? It doesn't look much different from the first example. Our car is still tightly coupled to our beloved MooseEngine™. So? Where do we set (or inject) our car's engine ?

Introducing Dependency Injection

As its name says, Dependency Injection is all about injecting dependencies, or simply said, setting relations between instances. Some people refer to it as being the Hollywood principle "Don't call me, we'll call you". I prefer calling it the "bugger" principle: "I don't care who you are, just do what I ask". In our first example, a Car depended on an Engine's concrete class called MooseEngine. When an class A depends on another class B, and that B's implementation is set directly in A, we say that A is tightly coupled to B. As we've seen in the second example, we have decided to use the Engine interface instead of the MooseEngine™ concrete class to make the Car more flexible. Moreover, we decided not to define the engine's concrete implementation. In other words, we have made our Car class loosely coupled. The Car doesn't depend on any concrete class of Engine anymore. Where do we indicate which Engine to use then ? That's where Dependency Injection comes. Instead of setting the concrete Engine class in the Car class, the concrete Engine class is injected from the outside. How do we do that?

1. Using constructor based injection

One way to set dependencies is to pass the concrete implementation of the depending class to the constructor. Our Car class would become:
public class Car {  private Engine engine;   public Car(Engine engine) {   this.engine = engine;  } } 
We could then create a Car using any kind of engine. For example, one car using the great MooseEngine™ and another one using the crappy SlowEngine:
public class Test {   public static void main(String[] args) {    Car myGreatCar = new Car(new MooseEngine());   Car hisCrappyCar = new Car(new SlowEngine());  } } 

2. Using setter based injection

Another common way to set dependencies is to use setter methods. Using setter methods is recommended instead of the constructor when many dependencies need to be injected. Our car class would then be written that way:
public class Car {  private Engine engine;   public void setEngine(Engine engine) {   this.engine = engine;  } } 
It looks very similar to the constructor based injection, doesn't it? We would then implement the same cars we have used above the following way:
public class Test {   public static void main(String[] args) {    Car myGreatCar = new Car();   myGreatCar.setEngine(new MooseEngine());   Car hisCrappyCar = new Car();   hisCrappyCar.setEngine(new SlowEngine());  } } 

Using Dependency Injection for Unit Testing

If you compare the first example of the Car class, and the one using setter based injection, you might think that some extra steps were needed to make the Car class using Dependency Injection. That's right, you had to write a setter method. But you can feel how rewarding this extra work is when unit testing. If you are not confident about what unit tests are, I recommend this Campfire Story on Evil Unit Tests. Our Car example is so simple that it does not illustrate well how useful Dependency Injection is for unit testing. We'll leave cars, and consider the example provided in the forementioned Campfire Story, especially the part on using mocks for unit testing. We have a servlet class using a remote EJB to register animals in a farm:
public class FarmServlet extends ActionServlet {   public void doAction( ServletData servletData ) throws Exception {   String species = servletData.getParameter("species");   String buildingID = servletData.getParameter("buildingID");   if ( Str.usable( species ) && Str.usable( buildingID ) ) {    FarmEJBRemote remote = FarmEJBUtil.getHome().create();    remote.addAnimal( species , buildingID );   }  } } 

You have already noticed that FarmServlet is tightly coupled to the FarmEJBRemote instance, which was retrieved via a call to "FarmEJBUtil.getHome().create()". It makes it very hard to test. When unit testing, we don't want to use any database. We don't want to access an EJB server either. That would make unit tests both difficult to execute and slow. So in order to unit test the FarmServlet class smoothly, we'd better make it loosely coupled. To remove the tight dependency between FarmServlet and FarmEJBRemote, we could use a setter based injection:
public class FarmServlet extends ActionServlet {  private FarmEJBRemote remote;   public void setRemote(FarmEJBRemote remote) {   this.remote = remote;  }       public void doAction( ServletData servletData ) throws Exception {   String species = servletData.getParameter("species");   String buildingID = servletData.getParameter("buildingID");   if ( Str.usable( species ) && Str.usable( buildingID ) ) {    remote.addAnimal( species , buildingID );   }  } } 

In the real deployment package, we will make sure that an instance of FarmServlet's remote member will be properly injected via "FarmEJBUtil.getHome().create()". In our unit test, we will use a dummy mock class to act like a FarmEJBRemote. In other words, we will make a mock class implementing FarmEJBRemote:
class MockFarmEJBRemote implements FarmEJBRemote {   private String species = null;  private String buildingID = null;  private int nbCalls = 0;   public void addAnimal( String species , String buildingID )  {   this.species = species ;   this.buildingID = buildingID ;   this.nbCalls++;  }   public String getSpecies() {    return species;  }  public String getBuildingID() {   return buildingID;  }  public int getNbCalls() {   return nbCalls;  } }  public class TestFarmServlet extends TestCase {   public void testAddAnimal() throws Exception {   // Our mock acting like a FarmEJBRemote   MockFarmEJBRemote mockRemote = new MockFarmEJBRemote();   // Our servlet. We set our mock to its remote dependency   FarmServlet servlet = new FarmServlet();   servlet.setRemote(mockRemote);                // just another mock acting like a ServletData   MockServletData mockServletData = new MockServletData();     mockServletData.getParameter_returns.put("species","dog");   mockServletData.getParameter_returns.put("buildingID","27");    servlet.doAction( mockServletData );   assertEquals( 1 , mockRemote.getNbCalls() );   assertEquals( "dog" , mockRemote.getSpecies() );   assertEquals( 27 , mockRemote.getBuildingID() );  } } 

That's it! We've got an easy to test FarmServlet.
To sum up some important points:
  • Use interfaces instead of using concrete classes to illustrate a dependency.
  • Avoid to implicitly set the concrete implementation of a dependency in the class itself.
  • Concrete implementation of a dependency may be set in various ways, including constructor based injection or setter based injection.
  • Dependency injection makes unit testing very flexible.

Dependency Injection - What is Scope?

Dependency Injection - What is Scope?

by Dhanji R. Prasanna

This article is excerpted from the upcoming book Dependency Injection by Dhanji R. Prasanna and published by Manning Publications. It introduces the concept of scope and the role it plays in application design. For the table of contents, the Author Forum, and other resources, go tohttp://www.manning.com/prasanna/.

In one sentence, scope is a fixed duration of time or method calls in which an object exists. In other words, a scope is a context under which a given key refers to the same instance. Another way to look at this is to think of scope as the amount of time an object's state persists. When the scope context ends, any objects bound under that scope are said to be out of scope and cannot be injected again in other instances.

State is important in any application. It is used to incrementally build up data or responsibility. State is also often used to track the context of certain processes, for instance, to track objects in the same database transaction.

In this article we'll talk about some of the general purpose scopes: singleton and no-scope. These are scopes that are universally applicable in managing state. We'll also take a look at managing state in specific kinds of applications, particularly the Web. Managing user-specific state is a major part of scoping for the web, and this is what the request, session, flash and conversation scopes provide. We'll look at a couple of implementations of these with regard to Guice and Spring, and how they may be applied in building practical web applications. First, a primer on scope.

Understanding Scope

The real power of scope is that it you can model the state of your objects declaratively. By telling the injector that a particular key is bound under a scope, you can move the construction and wiring of objects to the injector's purview. This has some important benefits:

  • Let the injector manage the latent state of your objects
  • Ensure that your services get new instances of dependencies as needed
  • Implicitly separate state by context (for example, two HTTP requests imply different contexts)
  • Reduce the necessity for state-aware application logic (which makes code much easier to test and reason about)

Scope properly applied means that code working in a particular context is oblivious to that context. And it is the injector's responsibility to manage these contexts. Not only does this mean that you have an added separation between infrastructure and application logic, but also that the same services can be used for many purposes simply by altering their scopes. Take this example of a family bathroom and their toothpaste:

family.give("Joanie", injector.getInstance(Toothpaste.class)); 
 family.give("Jackie", injector.getInstance(Toothpaste.class));
  family.give("Sachin", injector.getInstance(Toothpaste.class));  

Simply looking at this code we can say that the Toothpaste is used by Joanie first, then Jackie and finally by Sachin. We might also guess that each family member receives the same tube of toothpaste. If the tube were especially small, Sachin might be left with no paste at all (as per figure 1).


Figure 1: The injector distributes the same instance of toothpaste to all family members

This is an example of context: all three family members use the same bathroom, and therefore have access to the same instance of Toothpaste. It is exactly the same as the following program, using construction by hand:

Toothpaste toothpaste = new FluorideToothpaste();    
family.give("Joanie", toothpaste); 
 family.give("Jackie", toothpaste); 
 family.give("Sachin", toothpaste);  

If this were the whole life of the injector, then only one instance of Toothpaste is ever created and used. In other words, Toothpaste is bound under singleton scope. If however, each family member had their own bathrooms (each with its own tube of toothpaste) then the semantics would change considerably (as shown in figure 2).


Figure 2: The injector now creates a new toothpaste instance for each family member

  family.give("Joanie", injector.getInstance(Toothpaste.class)); 
 family.give("Jackie", injector.getInstance(Toothpaste.class));  
family.give("Sachin", injector.getInstance(Toothpaste.class));  

Nothing has changed in code, but now a new instance of Toothpaste is available to each family member. And now there is no danger of Sachin being deprived of toothpaste by Joanie or Jackie. In this case, the context under which each object operates is unique (that is, their own bathrooms). You can think of this as the opposite of singleton scoping. Technically this is like having no scope at all.

The No-scope (or default scope)

In a sense, no-scope fulfills the functions of scope, as it:

  • provides new instances transparently,
  • is managed by the injector, and
  • associates a service (key) with some context

Or does it? The first two points are indisputable. However, there arises some difficulty in determining exactly what context it represents. To get a better idea of no-scope's semantics, let's dissect the example of the toothpaste from earlier. We saw that it took no change in the use of objects to alter their scope. The family.give() sequence looks exactly the same for both singleton and no-scope:

  family.give("Joanie", injector.getInstance(Toothpaste.class));  
family.give("Jackie", injector.getInstance(Toothpaste.class)); 
 family.give("Sachin", injector.getInstance(Toothpaste.class));  

Or, expanded using construction by hand (modeled in figure 3):

  Toothpaste toothpaste = new FluorideToothpaste();
  family.give("Joanie", toothpaste);   
 toothpaste = new FluorideToothpaste(); 
 family.give("Jackie", toothpaste);   
 toothpaste = new FluorideToothpaste(); 
 family.give("Sachin", toothpaste);  

Figure 3: Each member of the family receives their own instance of Toothpaste

In no-scope, every reference to Toothpaste implies a new toothpaste instance. We likened this to the family having three bathrooms, one for each member. However, this is not exactly accurate. For instance, if Sachin brushed his teeth twice:

  family.give("Joanie", injector.getInstance(Toothpaste.class)); 
 family.give("Jackie", injector.getInstance(Toothpaste.class)); 
 family.give("Sachin", injector.getInstance(Toothpaste.class));  
 family.give("Sachin", injector.getInstance(Toothpaste.class));  

...you would end up with a total of four Toothpaste instances (see figure 4).


Figure 4: There are now four instances of Toothpaste, for each use

Now, in our conceptual model, there were only three bathrooms. But in practice there were four tubes of toothpaste. This means that no-scope cannot be relied on to adhere to any conceptual context. No-scope means that every time an injector looks for a given key (one bound under no-scope), it will construct and wire a new instance. Furthermore, let's say Sachin took Joanie on vacation and only Jackie was left at home. She would brush her teeth once, as follows:

  family.give("Jackie", injector.getInstance(Toothpaste.class));  

And this would mean only one instance of Toothpaste was ever created for the life of the application. This was exactly what happened with singleton scoping, but this time it was purely accidental that it did. Given these two extremes, it is difficult to lay down any kind of strict rules for context with no-scope. You could say, perhaps, that no-scope is a split-second scope where the context is entirely tied to referents of a key. This would be a reasonable supposition. Contrast singleton and no-scope in figure 5.


Figure 5: Timeline of contexts, contrasting singleton and no-scopes

No-scope is a very powerful tool for working with injector-managed components. This is partly because it allows a certain amount of flexibility in scaling upward. Dependents that exist for longer times (or in wider scopes) may obtain no-scoped objects as they are required, safely. Granny obtained new instances of an Apple on each use (see listing 1, modeled in figure 6).


Figure 6: Granny obtains instances of Apple (bound to no scope) from a provider

Listing 1: An example of no-scope using the provider pattern
  public class Granny {     public Provider appleProvider;     
 public void eat() {  
  appleProvider.get().consume(); 
 |#1    appleProvider.get().consume();  |#2   }  } 
  (Annotation) <#1 Two new apples created> 

In listing 1, the eat() method uses a provider to retrieve new instances, just as we did for Toothpaste earlier. Here Apple is no-scoped.

Guice and Spring differ in nomenclature with regard to the no-scope. Spring calls it as the prototype scope. The idea being that a key (and binding) is a kind of template (or prototype) for creating new objects. In the following example, no-scoping enabled multiple threads to see independent instances of an object (modeled in figure 7):

     scope="prototype"/>   scope="prototype"/>   
  safe" class="UnsafeObject" init-method="init" scope="prototype">               


Figure 7: UnsafeObject and both its dependencies were no-scoped

This object was actually safe, because any dependents of key safe were guaranteed to see new, independent instances of UnsafeObject. Like singleton, the name prototype comes from the Gang of Four book on Design Patterns. I prefer to refer to it as no-scope, largely because it is a more descriptive name. Like Guice, PicoContainer also assumes the no-scope if a key is not explicitly bound to some scope:

  PicoContainer injector = new DefaultPicoContainer();
  injector.addComponent(Toothpaste.class);   
 family.give("Joanie", injector.getComponent(Toothpaste.class));
  family.give("Jackie", injector.getComponent (Toothpaste.class));  ...  

Almost no difference at all.

NOTE

You will sometimes also hear no-scope referred to as the default scope. This is a less descriptive name, and typically connotes either Guice or PicoContainer (since they default to the no-scope).