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

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.

Leave a Comment