Sunday, November 18, 2012

Bookmark and Share

Watching a talk from Square's CTO Bob Lee, I just learned about Dagger, a new dependency injection framework for Java and Android which is currently in the works at Square, Inc.

Considering the number of existing DI solutions in the Java space – e.g. CDI, Google Guice and Spring – one might wonder whether the world really needs yet another DI framework. According to Bob's talk, Dagger (a pun on "directed acyclic graph") is the attempt to create a modern and fast DI framework based on the insights gained during development and usage of Guice (Bob was the founder of the Guice project at Google). And indeed does Dagger come up with some quite interesting ideas which I'd like to discuss in more detail in the following.

Overview

Dagger is centered around the annotations for dependency injection defined by JSR 330 (which Bob Lee co-led). This is a good thing because it increases portability of your code between different DI solutions.

Dependencies are retrieved by annotating fields or constructors with @Inject:

1
2
3
4
5
6
7
8
9
10
11
public class Circus {

    private final Artist artist;

    @Inject    
    public Circus(Artist artist) {
        this.artist = artist;
    }

    //...
}

To satisfy dependencies, Dagger creates the required objects using their @Inject-annotated constructor (in turn creating and passing any dependencies) or the default no-args constructor.

Where that's not possible (e.g. when an implementation of an interface needs to be injected) provider methods can be used. Provider methods must be annotated with @Provides and be defined in a class annotated with @Module like this:

1
2
3
4
5
6
@Module
public class CircusModule {
    @Provides Artist provideArtist() {
        return new Juggler();
    }
}

The @Module annotation is also used to define the entry point of an application:

1
2
3
4
@Module( entryPoints=CircusApp.class )
public class CircusModule {
    //...
}

This entry point represents the root of the object graph managed by Dagger. As we'll see in a moment, explicitly defining the root allows for compile-time validation of the dependency graph. An instance of the entry point type can be retrieved from the ObjectGraph class, passing the module(s) to create the graph from:

1
2
3
ObjectGraph objectGraph = ObjectGraph.create(new CircusModule());
CircusApp circus = objectGraph.get(CircusApp.class);
circus.startPerformance();

Dagger also also provides support for qualifiers, lazy injection, injection of providers and more. The project's web site gives a good overview. Apart from that it's interesting to see what Dagger deliberately does not support to avoid an increased complexity:

  • Circular dependencies between objects
  • Method injection
  • Custom scopes (Objects are either newly created for each injection or singleton-scoped)

Code generation

DI frameworks usually make intensive use of reflection to examine annotations, find injection points, create managed objects etc. While reflection today isn't as expensive as it used to be in earlier years, it still can take a considerable amount of time to create large object graphs with lots of dependencies.

Dagger tries to improve upon that with the help of code generation. It provides a JSR 269 based annotation processor which is used at compile time to create an adapter class for each managed type. These adapter classes contain all the logic required at run time to set up the object graph by invoking constructors and populating references to other objects, without making use of reflection.

This approach promises performance benefits over reflection-based ways for creating object graphs typically used by DI frameworks. On my machine Dagger needed roughly half the time to initialize the graph of the CoffeeApp example using the generated classes compared to using reflection (which it also supports as fallback). Of course this is by no means a comprehensive benchmark and can't be compared with other frameworks but it surely shows the potential of the code generation approach.

The annotation processor also performs a validation of the object graph and its dependencies at compile time. So if for instance no matching type (or more than one) can be found for a given injection point, the build will fail with an error message describing the problem. This helps in reducing turn-around times compared to discovering this sort of error only at application start-up. Implementing this sort of checks using an annotation processor makes them available in IDEs (which typically can integrate annotation processors) as well as headless builds, e.g. on a CI server.

Object graph visualization

Not mentioned in the documentation, Dagger also provides an annotation processor which generates a GraphViz file visualizing the object graph. This may be useful to get an understanding of unknown object graphs. The following shows the graph from the CoffeeApp example:

Summary

Dagger is a new dependency injection framework for Java and Android.

While it's still in the works (the current version is 0.9 and there are still some apparent bugs), I find the concept of using an annotation processor for validating the object graph at compile time and generating code for a faster initialization at runtime very interesting. In particular on mobile devices fast start up times are essential for a good user experience.

I also like the idea of leaving out features which might provide some value but would add much complexity. One thing I'm missing though is some sort of interceptor or decorator mechanism. This would be helpful for implementing typical cross-cutting concerns.

It'll definitely be interesting to see how the code generation approach works out in practice and whether other DI solutions possibly adapt that idea.

27 comments:

Gopi Krishna said...

Dependency Injection is a software design pattern in which components are given their dependencies instead of hard coding them within the component. This relieves a component from locating the dependency and makes dependencies configurable. This helps in making components reusable, maintainable and testable.

AngularJS provides a supreme Dependency Injection mechanism. Know More: AngularJS Training in Chennai

Priya Kannan said...

This information really worth saying, i think you are master of the content and thank you so much sharing that valuable information and get new skills after refer that post.
PEGA Training in Chennai

Freddie King said...

Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
www.mcdonaldsgutscheine.net | www.startlr.com | www.saludlimpia.com

Durante said...

Thanks for posting...

Rangga Alexandra said...

Manfaat Daun Kemuning Untuk Menurunkan Berat Badantips bagi penderita jantung bengkak

Harish said...

Thank you for sharing this useful information.

Angularjs course in Chennai | Angularjs Training in Chennai

simbu said...

It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
java training in omr

java training in annanagar | java training in chennai

java training in marathahalli | java training in btm layout

java training in rajaji nagar | java training in jayanagar

amilu B said...

I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community.
python training in chennai | python training in bangalore

python online training | python training in pune

python training in chennai | python training in bangalore

python training in tambaram |

pooja saravanan said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 

Hadoop Training in Chennai

Hadoop Training in Bangalore

Big data training in tambaram

Big data training in Sholinganallur

Big data training in annanagar

Big data training in Velachery

Ram priya said...

Fantastic work! This is the type of information that should follow collective approximately the web. Embarrassment captivating position Google for not positioning this transmit higher! Enlarge taking place greater than and visit my web situate
Data Science Training in Chennai
Data science training in bangalore
Data science online training
Data science training in pune
Data science training in kalyan nagar
selenium training in chennai

digi mark said...

Nice post. By reading your blog, i get inspired and this provides some useful information. Thank you for posting this exclusive post for our vision. 


rpa training in Chennai

rpa training in pune

rpa online training

rpa training in bangalore

rpa training in Chennai

rpa training in Chennai

rpa training in velachery

rpa training in tambaram

saran latha said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
Devops Training in Chennai

Devops Training in Bangalore

amala said...

Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.

rpa training in Chennai | rpa training in pune

rpa training in tambaram | rpa training in sholinganallur

rpa training in Chennai | rpa training in velachery

rpa online training | rpa training in bangalore

sai said...

Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries.
python training in tambaram
python training in annanagar
python training in OMR

sudhagar raja said...

Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
java training in omr | oracle training in chennai

java training in annanagar | java training in chennai

sai said...

I was looking for this certain information for a long time. Thank you and good luck.
python online training
python training in OMR
python training in tambaram
python training in annanagar

Revathy A said...

All the points you described so beautiful. Every time i read your i blog and i am so surprised that how you can write so well.


angularjs Training in chennai
angularjs Training in chennai

angularjs-Training in tambaram

angularjs-Training in sholinganallur

angularjs-Training in velachery

Sri Nithya said...

Excellent and useful blog admin, I would like to read more about this topic.
Angularjs Training in Chennai
Angularjs Training Institute in Chennai
Angularjs Training center in Chennai
Angularjs Training Chennai

Ram priya said...

This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
Data science course in tambaram | Data Science course in anna nagar
Data Science course in chennai | Data science course in Bangalore
Data Science course in marathahalli | Data Science course in btm

Sri Nithya said...

Thanks for sharing this information admin, it helps me to learn new things. Continue sharing more like this.
DevOps certification Chennai
DevOps Training in Chennai
DevOps Training institutes in Chennai
RPA Training in Chennai
Blue Prism Training in Chennai
UiPath Training in Chennai

sumathi s said...

I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
industrial safety course in chennai

Unknown said...

We are DevOps Training in Bangalore,Chennai, Pune using Class Room. myTectra offers Live Online DevOps Training Globally

Pankaj Singh said...

Nice Blog, Thank you so much sharing with us. Visit for
Web Designing Company in Delhi

chitra pragya said...

Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…

angularjs online Training

angularjs Training in marathahalli

angularjs interview questions and answers

angularjs Training in bangalore

angularjs Training in bangalore

Ananya Krishnan said...

Good job in presenting the correct content with the clear explanation. The content looks real with valid information. Good Work

DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

Good to learn about DevOps at this time.


devops training in chennai | devops training in chennai with placement | devops training in chennai omr | devops training in velachery | devops training in chennai tambaram | devops institutes in chennai

Unknown said...

your post is the very organized way and easily understandable. Doing a good job. Thank you for sharing this content.
rpa training in chennai | rpa training in velachery | rpa training in chennai omr


Unknown said...

myTectra a global learning solutions company helps transform people and organization to gain real, lasting benefits.Join Today.Ready to Unlock your Learning Potential !Read More...