Guice

Dependency Injection Framework

  • (2 Pages)
  • +
  • 1
  • 2

27 Replies - 3869 Views - Last Post: 12 July 2010 - 02:06 PM

#1 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Guice

Post icon  Posted 06 July 2010 - 04:26 PM

Google provides this nifty and very helpful framework called Guice. It is a dependency injection framework for Java 5 and above. For those who don't know what dependency injection is, as usual, Wikipedia introduces the idea here.

In summary though, dependency injection allows you to configure how and where your objects receive their external dependencies. It also eliminates all of the overhead/boiler-plate code associated with obtaining those dependencies. Another benefit is that the configurations for dependencies can be swapped out at run time to avoid recompiling or recoding a project.

With dependency injection, you just say "these are the external dependencies my object needs to function." Guice will do dependency analysis on those dependencies, and their dependencies, and so on until they can all be resolved and provided.

Here is a quick example of Guice in action:

You might have a car class called Car.java:

import car.Exterior;
import car.Interior;
import car.Engine;
import car.Chassis;

class Car {
    private final Exterior exterior;
    private final Interior interior;
    private final Engine engine;
    private Chassis chassis;

    @Inject
    public Car(Engine engine, Exterior exterior, Interior interior, Chassis chassis) {
        this.engine = engine;
        this.exterior = exterior;
        this.interior = interior;
        this.chassis = chassis;
    }
}



Notice the @Inject annotation. That is a Guice annotation which signifies that our constructor is an injection point for dependencies. This means Guice will analyze all the parameters types and provide each parameters based on how it was configured.

To configure Guice, you setup modules which contain various ways of providing dependencies. The easiest and most common is a binding. A binding maps a class type to an implementation. So you might have a PorscheModule that looks like this in PorscheModule.java:

import car.*;

class PorscheModule extends AbstractModule {
    protected void configure() {
        bind(Engine.class).to(PorscheEngine.class);
        bind(Exterior.class).to(PorscheExterior.class);
        bind(Interior.class).to(PorscheInterior.class);
        bind(Chassis.class).to(PorscheChassis.class);
    }
}



So above we have setup a module which configures how each of the dependencies for Car should be provided. Next we put it all together in Main.java:
class Main {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new PorscheModule());
        Car myCar = injector.getInstance(Car.class);
    }
}



In this case, you would get a porsche from Guice because that's what module was loaded into it. Sweet!

So you can basically think of Guice as a fancy, dynamic, configurable factory that does all the work of dependency analysis and creation for you.

Here's the Guice creators talking all about how Guice will change your life:


Is This A Good Question/Topic? 3
  • +

Replies To: Guice

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10565
  • View blog
  • Posts: 39,104
  • Joined: 27-December 08

Re: Guice

Posted 06 July 2010 - 05:08 PM

Looks interesting, but I can't say that I'm sold. I like the fact that you are able to dynamically inject at runtime. However, Java provides all of these tools already with the Reflection API, albeit this is a little less work, though. After looking through the documentation, I'd say this is good for the less advanced work and more intermediate-level programmers who have a good handle on OOP, and for jobs that lie somewhere between modifying the structure and contents of your program's components. But for anything significantly more advanced or requires modifying or working with the structure of the program, I'd Reflection is probably the better tool. Though they do seem to complement each other fairly well when I look back at it.

Good find. :^:
Was This Post Helpful? 0
  • +
  • -

#3 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Guice

Posted 06 July 2010 - 05:17 PM

How are you going to use reflection to resolve a class's dependencies without essentially implementing a DI framework?
Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10565
  • View blog
  • Posts: 39,104
  • Joined: 27-December 08

Re: Guice

Posted 06 July 2010 - 05:29 PM

As I said, a little more work, but it can be done. For instance, you can use the Constructor class to instantiate an Object using the newInstance(Object... params) method, and you can dynamically invoke methods. If you really want to get into injecting, take a look at the Proxy and Method classes. This is, more or less, what I've been working on at my internship.

The nice thing about Guice is that it packages it into a friendlier framework, as reflection is not for anyone who doesn't already have an expertise in Java.

Edit: So more or less, you'd be re-creating the framework, but reflection is a lot more powerful than Guice.

This post has been edited by macosxnerd101: 06 July 2010 - 05:31 PM

Was This Post Helpful? 0
  • +
  • -

#5 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Guice

Posted 06 July 2010 - 05:32 PM

Right, that's all Guice is doing. Just getting a handle on a constructor and then referencing a Module's configured bindings to determine what parameters to pass into the constructor.

Guice uses reflection so I'm not sure how reflection can be more powerful than a framework that uses reflection.

This post has been edited by Dark_Nexus: 06 July 2010 - 05:32 PM

Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10565
  • View blog
  • Posts: 39,104
  • Joined: 27-December 08

Re: Guice

Posted 06 July 2010 - 05:38 PM

Guice only handles structure, while Reflection deals with functionality as well. With some fancy tricks, you can use the Proxy and Method classes to dynamically change functionality. Guice, more or less, waters down reflection into a nice package, but by doing so doesn't extend (no pun intended ;)) to the other features of reflection. It is only candy-coating a part of the whole picture.

The way I see it is that Guice is nice for intermediate programmers that aren't ready for reflection, then reflection for the advanced programmers that are doing some really advanced topics. If you want more power than reflection, ie., dynamically creating functionality, you're stuck with writing bytecode for the JVM to pass to a ClassLoader. I took a look at this, and I said sorry, no way in hell. Not until I'm doing Ph.D level research (for pbl's MIT Ph.D thesis paper, of course :P).
Was This Post Helpful? 0
  • +
  • -

#7 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Guice

Posted 06 July 2010 - 05:43 PM

Guice isn't meant to replace reflection, it's meant to implement dependency injection via a framework. Dependency injection focuses on the external structures in which a class depends on. I think you're missing the point. It's not trying to dynamically change the functionality of a class, it's just trying to resolve a class's external dependencies.

If you want to be able to manipulate functionality at run time, you don't use Java, you use a dynamically typed language.

This post has been edited by Dark_Nexus: 06 July 2010 - 05:54 PM

Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10565
  • View blog
  • Posts: 39,104
  • Joined: 27-December 08

Re: Guice

Posted 06 July 2010 - 06:27 PM

I understand the point. To summarize my scattered thoughts, I'm more saying this is a good start at making reflection more friendly, as by implication, satisfying dependencies and being able to change them at runtime allows for modification of the state of the program at any given moment, which can alter functionalities via polymorphism. Though I'd like to see more of this with functionality (ie., Method and Proxy classes) rather than just the state of the Objects. Now that I think about it some more, it is definitely possible with a little extra elbow grease to accomplish dynamic changing of functionalities as well in the same ways as reflection does, though I'm not so sure about substituting for Proxies.

Quote

If you want to be able to manipulate functionality at run time, you don't use Java, you use a dynamically typed language.

Which is exactly where reflection comes in handy. Either by a happy accident or intentional design (as Java was supposedly not designed to support Method pointers), the use of the Method and Proxy classes allows for this.

This post has been edited by macosxnerd101: 06 July 2010 - 06:31 PM

Was This Post Helpful? 0
  • +
  • -

#9 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Guice

Posted 06 July 2010 - 06:37 PM

The proxy class just allows you to swap out concrete implementations of an interface at run time, you're not dynamically generating methods at run time based on program state. You are swapping out statically defined functions at run time.

This post has been edited by Dark_Nexus: 06 July 2010 - 06:47 PM

Was This Post Helpful? 0
  • +
  • -

#10 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10565
  • View blog
  • Posts: 39,104
  • Joined: 27-December 08

Re: Guice

Posted 06 July 2010 - 06:44 PM

For exactly what I'm doing at my internship, which requires dynamic functionality on the Java platform for Android. I actually started on the DTD today for my markup language for dynamic GUIs with dynamic events to replace UIML, and in order to make it useful beyond UIML, I need functionality of this scope in Java which only comes from Reflection. And in all honesty, this is the way I see GUIs evolving, so (if I'm right) languages are going to have to eventually be expanded to include some reflection ability or they will become legacy languages.

Edit: Yes- I am having to inject pre-defined functionality. This is more or less the point of the project (I can't go much more into the project, as that's part of what we're patenting). The creating dynamic functionality part would require writing JVM bytecode, which doesn't appeal to me at this very moment.

This post has been edited by macosxnerd101: 06 July 2010 - 06:49 PM

Was This Post Helpful? 0
  • +
  • -

#11 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Guice

Posted 06 July 2010 - 07:00 PM

Quote

The creating dynamic functionality part would require writing JVM bytecode, which doesn't appeal to me at this very moment.


At that point you would just be doing a lot of work to accomplish what other languages already do, but better.

Quote

languages are going to have to eventually be expanded to include some reflection ability or they will become legacy languages.


Languages like Python, Ruby, Lisp, have all been doing exactly what you are trying to do but for 10, 20, 30, 40 years. What you're preaching as the future has been here a long, long time.

If you really want to have fun with the power of dynamic typing and meta programming, then I would recommend not using Java for the time being. Although, Java 7 is supposed to feature lambda expressions which will most likely allow you to treat functions as first class citizens.

This post has been edited by Dark_Nexus: 06 July 2010 - 07:09 PM

Was This Post Helpful? 0
  • +
  • -

#12 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10565
  • View blog
  • Posts: 39,104
  • Joined: 27-December 08

Re: Guice

Posted 06 July 2010 - 07:28 PM

As has Objective-C, which makes this task easier for my co-worker doing this on the iPhone. For the Android app, though, I have to use Java. I've started Functional Programming a little with Erlang, and I'll look into Ruby and Scala or Clojure when I have a spare moment.
Was This Post Helpful? 0
  • +
  • -

#13 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Guice

Posted 06 July 2010 - 07:30 PM

Languages are tools. If the tool doesn't do what you want it to do, then switch tools. Don't try to make a tool do something it wasn't meant to do. You are just going to waste a lot of time and end up with an inferior tool compared to one that was originally intended for that purpose.

You are trying to make a statically typed language dynamic. It would be like me looking at Python and saying "boy, the lack of explicit types makes this language less safe than something explicitly typed like Java" and then trying to add explicit types to Python. I am working against the paradigm and the typing system when I could just switch to Java.

This post has been edited by Dark_Nexus: 06 July 2010 - 07:32 PM

Was This Post Helpful? 0
  • +
  • -

#14 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Guice

Posted 06 July 2010 - 08:42 PM

View Postmacosxnerd101, on 06 July 2010 - 05:38 PM, said:

The way I see it is that Guice is nice for intermediate programmers that aren't ready for reflection...


Just out of curiosity, how long have you been programming professionally? Do you consider yourself an "advanced" programmer because you know how to use reflection - a basic Java SE API? Frankly, I think reflection is more of an intermediate topic. It's something I use when it fits (although it is fairly limited), but overuse of reflection can lead to inefficient code in some cases, so watch out for that. No offense, but I don't think you really understand the purpose of the IoC design pattern or you wouldn't be comparing it to reflection. It's been around for quite a while - much longer than Guice has existed.

I know you said you were averse to dynamic byte code generation, but cglib is a great little library for doing dynamic stuff that you can't normally do in Java. It's also behind many popular frameworks (including Spring, Hibernate, and, I believe, Guice). It might make your job a bit easier.

Edit:Actually I forgot you were writing Android apps. In that case cglib is probably out of the question and you may be stuck with just reflection.

@Dark_Nexus: Guice is a handy DI framework, no doubt. I wrote some code with it a few years ago (1.0) just after Crazy Bob Lee did his first Google tech talk on the topic. I found it to be a very good, if simple, DI framework. It was evolutionary at the time in one respect because it was all Java and used annotations for injection, whereas Spring, the leading DI framework of the time, was still XML-only. Spring IoC has since caught up in my opinion and even has an all Java DI framework called JavaConfig, which is similar to Guice in some ways. Personally, I prefer Spring IoC because I can use XML, annotations, or (more commonly) a combination of the two as necessary. I find that the use of a Spring IDE plugin completely mitigates any compile-time or refactoring issues with using XML. It also has integration with a huge number of other frameworks because it's been around for so long and is so widely used. I've been meaning to revisit Guice 2.0 just to see what's new, but I have so many other things in the queue that it may have to wait until 3.0. :)

This post has been edited by Programmist: 06 July 2010 - 08:47 PM

Was This Post Helpful? 0
  • +
  • -

#15 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10565
  • View blog
  • Posts: 39,104
  • Joined: 27-December 08

Re: Guice

Posted 06 July 2010 - 10:54 PM

Quote

Just out of curiosity, how long have you been programming professionally?

I'll give you two answers, pick the one you like better.

From March-June, I was working as the Project Manager and Lead Developer for my nonprofit website project in web design and development class, so 4 or so months. I linked to my blog entry about it, which goes into greater detail about the scope of the project if you're interested.

If you don't feel that qualifies as professional development, then I've been programming professionally for 3 days during my internship.

Quote

Do you consider yourself an "advanced" programmer because you know how to use reflection - a basic Java SE API? Frankly, I think reflection is more of an intermediate topic. It's something I use when it fits (although it is fairly limited), but overuse of reflection can lead to inefficient code in some cases, so watch out for that.

As I haven't been out in the real-world that long, my experience is fairly limited to helping out on the Java forum, the academic assignments I've had (to give you an idea of the difficulty, the most challenging programming course I've been in is AP CS, which is on par with a college intro class, so nothing too challenging, though our class was the most rigorous and comprehensive in the country as we have school issued laptops and someone who has been in the IT Field for 10+ years teaching the course), and a couple things I've done on the side and on my own, including some college level work.

I'm guessing you're a senior developer, so compared to you, probably not all that advanced. However, I was hired on the spot for my internship at an IT Consulting Firm by the owner, who has a Ph.D in Computer Science, and I've been making valuable contributions since Day 1. In fact, when he hired me, he told me I was probably on par with some his employees. Keep in mind that I'm a high school student. So I guess for my age, I'm advanced. Though if you are implying that I feel I'm advanced for being able to pick up an API, then no, that isn't the case.

In the case of what I'm doing with Android, Reflection fits here. More or less, I'm working to develop a markup language that expands on some of the shortcomings of UIML (like functionality), and use the mobile app to render. So as this is being rendered, not compiled, I need to use reflection. I wish there was a better solution on the mobile platform than reflection, but there doesn't seem to be. I do agree with you (and recognized before hand) that reflection has a niche purpose, and if there is a better solution, to utilize it. And it doesn't surprise me that overuse of Reflection can slow things down.

Thanks for the link to the library. I'll keep that in mind. :)

@: Except that Sun provided the functionality, though maybe not in the friendliest manner.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2