Can anyone provide a clear explanation of why Google Guice is useful?

sanity picture sanity · Sep 22, 2009 · Viewed 24.4k times · Source

I've read about Google Guice, and understand the general issues with other approaches to dependency injection, however I haven't yet seen an example of someone using Guice "in practice" where its value becomes clear.

I'm wondering if anyone is aware of any such examples?

Answer

Joshua Partogi picture Joshua Partogi · Sep 23, 2009

Using Google Guice to provides ease in unit testing is only high-level advantage. Some people might not even use unit testing in their project. People has been using Spring/Dependency Injection more than only for unit testing.

The low level advantage of using Google Guice is a matter of cohesion in your application, your classes in the project can be loosely coupled between each other. I can provide a class for another class without them being dependent to each other.

Consider this example:

public class A {

}

public class B {
  A a = new A();
}

Class B would be tightly coupled to Class A, or in other words it is dependent to class A's existence.

But with Guice I can instead make it loosely coupled like this:

public class B {
    private A a;
    
    @Inject
    public B(A a) {
        this.a = a;
    }
}

Class B is now loosely coupled to A, and Guice is responsible to provide the instance of A instead of B having to instantiate it. With this you can extend it to provide interface of A to B, and the implementation can be a Mock object if you want to unit test your apps.

Having said that we're only discussing the benefits of Dependency Injection so far. Beyond Dependency Injection, the benefits of using Google Guice is:

  1. Guice has a very clean implementation of constructor Injection. As you can see from the example you just add @Inject annotation constructor.
  2. Guice also has setter Injection using the same annotation.
  3. Having said that, the annotation based Injection is very clean approach compared to XML based injection like some other DI implementation.
  4. All of the dependency injection and configuration is using Java, so you are guaranteed to get a typesafety in your application by default.
  5. Guice has a very lightweight implementation of Aspect Oriented Programming (or maybe you can call it as a wrapper to the AOPAlliance AOP implementation). And the good thing of it is it doesn't generate stubs or what-so-ever.

That's the overview of it. But as you get deeper with Guice, there's so many more good things about it. A simple real life example is if you are using GWT with MVP implementation, the components/widgets in your GWT application are very loosely coupled and not tightly integrated to each other.