Dagger and Butter Knife vs. Android Annotations - android

I am evaluating Dependency Injection (DI) frameworks for an Android app. The top contenders are: Dagger (with Butter Knife) and Android Annotations. I understand that Dagger and ButterKnife are from the same source- square and they complement each other. Here're are the key matrices that I am looking for:
Ease of use (our build is based on Gradle and we use Android Studio IDE)
Testing support (we use Robotium for functional testing and RoboLectric for unit testing)
Performance (DI frameworks use reflection, which one is faster?)

AndroidAnnotations
uses compile time annotation processing. It generates a sub class with an underscore apppended to the original name (MyActivity_ generated from MyActivity). So to have it work you always have to use the generated class for references instead of your original class.
It has a very rich feature set, see the list of available annotations.
Butterknife
uses also compile time annotation processing, but it generates finder classes which are used by a central class (ButterKnife). This means that you can use your original class for referencing, but you have to call the injection manually. A copy from the ButterKnife introduction:
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.inject(this);
// TODO Use "injected" views...
}
The feature set is not so rich, ButterKnife supports view injection (AndroidAnnotations equivalent would be #ViewByIdand #ViewsById) and some event binding (for a complete list see the namespace directory here, just count the OnXXX event annotations).
Dagger
is a DI implementation for Android, similar to Guice. It also uses compile time annotation processing and generates object graphs which you use for manually injection. You distinguish between application object graph and scoped object graphs for injecting e.g. in activities. Here you see an Application.onCreate example:
#Override public void onCreate() {
super.onCreate();
objectGraph = ObjectGraph.create(getModules().toArray());
objectGraph.inject(this);
// use injected classes
}
I found it is harder to start with dagger, but this might be only my experience. However see some videos here for a better start: 1, 2
From the feature set point of view I would say that Dagger implements functionalities which could be compared to AndroidAnnotation's #EBean and #Bean functionality.
Summary
If you are comparing ease of use, testing support and performance I can't find much difference between using AndroidAnnotation and ButterKnife+Dagger. Differences are in the programming model (use classes with _ instead of using the original ones and call the injection manually) and in the feature set.
AndroidAnnotation gives you a full list of functionalities, but ties you to certain libraries. For example if you use it's rest api you have to use Spring Android. You also have annotations for features like OrmLite (#OrmLiteDao) regardless if you use OrmLite or not.
At the end it is a matter of taste, at least in my opinion.

Here is the Nice article in Dzone blog.
We to need to compare the features of each, such as :
Minimum Jars required
ActionBarSherlock compatibility
Injection for click listeners
POJO injection
Performance
Only Pojo Injection missing in butterknife! So looks like Butterknife is the winner!
Source

Google does ask specifically not to use dependency injection.
But by reading their request they seem to be referring more to the Guice and reflection based DI library's. Libraries such as android annotation use no reflection instead employing compile time generated code, while butterknife and dagger uses a small amount of reflection optimised for android but are supposedly slightly more powerful than android annotation. It really depends on the project and how much of a performance hit you are willing to take. In my opinion just using butterknife is sufficient to speed up code development by itself. If you need slightly more use android annotation and lastly if you are willing to take a slight performance hit due to reflection the best option without absolutely destroying performance with a powerhouse Guice based reflection use dagger + butterknife.

You should give a try at Toothpick.
Toothpick is (per the README):
pure java
fast, it doesn't use reflection but annotation processing
simple, flexible, extensible & powerful, robust & tested
thread safe
documented & Open Source
scope safe : it enforces leak free apps
test oriented : it makes tests easier
it works very well with Android or any other context based framework (such as web containers)
It can even be faster than Dagger 2 in most cases, and it's much simpler.
Note: Yes, I am one of the authors.

Use Android Annotations or Butterknife to ease your coding. But don't go for Roboguice! Roboguice forces your activies, fragments to extend to roboguice classes. Not fun, at all!
Dagger 2 is a much better option. You can use it along with Android Annotations if you'd like. I would just use Android Annotations for a simple app, but these days is good to work more with Dagger.

Seems like Google chooses dagger, as they are developing it jointly with Square, who created it.
Concerning Butterknife and Dagger themselves, there is the SO question difference-between-dagger-and-butterknife-android which clarifies how they complement each other.

The reddit-thread mentioned by #ChrLipp has someone who used all three on the same project, speaks highly of dagger+butterknife but also gives AndroidAnnotations its place:
For dependency injection, butterknife is used for Views, Dagger is
used for all objects and is highly recommended and Android Annotations
creates more of a framework for developing Android instead of
injecting objects into your classes so each library are quite
different from each other. Dagger is equivalent to Guice but is much
much faster. Dagger is more powerful then ButterKnife and Android
Annotations as it injects all objects rather than ButterKnife and
Android Annotations which only inject a certain set of objects.
Dagger can be a pain to setup and configure but is well worth it once
you have it done. But then again, because these are all quite
different from each other, it all depends on what your needs are for
the project.
Also, speaking of each one being quite different, in your project you
can use ButterKnife, Android Annotations and Dagger all in the same
project if you really want to. They each have the same idea but do
something different so you could use them all.

Eventually if you use one of the three, you'll have a hard time transitioning to Android's databinding. That's what's fastest if you need to consider performance:
https://developer.android.com/tools/data-binding/guide.html

Related

Using interfaces for ViewModels?

I am currently integrating architecture components into my app according to the official documentation and the sample apps provided by google (sunflower and todo-app). I realized that none of these use interfaces for ViewModels (the sunflower app does not even use interfaces for repositories).
My question is: is it reasonable to just omit the interfaces for ViewModels (including advantages and disadvantages)?
Is it reasonable to just omit the interfaces for ViewModels?
The below is quite general and applicable not just for ViewModels.
Advantages:
less code
Disadvantages:
won't be able to use most of the well-known design patterns;
won't be able to properly unit test classes (no mocking);
won't be able to properly use dependency injection frameworks;
code refactoring when using another concrete implementation.
The answer depends on the complexity of your ViewModel. If you are never going to create more than one implementation of an interface (including mocking), then there is no need to create the interface, so you can reduce the code and the overall maintenance burden.
That said the important things to consider are:
Can you unit test your view model, even without the interface (answer should be yes, otherwise you have some other problems IMO)
Can you still use a dependency injection framework (the answer is yes at least for some DI frameworks like Prism)
Are you only ever going to create one implementation of your ViewModel?
I believe that the mark of a well-designed ViewModel, should have a relatively simple implementation, and be easy to unit-test without having to resort to mocking.

AndroidAnnotations and Dagger 2

I'm reading about Dependency Injections and found 2 libs that get my attention, AndroidAnnotations and Dagger 2. What I saw is that AA has a lot of functionalities including DI, but most of the developers are using Dagger 2 for DI.
I was wondering what is the diference between DI with AA and DI with Dagger 2? If I use AA it means I don't need Dagger 2?
I couldn't find much information for DI with AA and comparison with other libraries.
Any info would help a lot.
I do not think AA and Dagger can be compared.
Dagger is a general dependency injection library, with lots of capabilities. It is designed to run on Android as well, but it does not need Android, it can be applied on pure Java projects. It has lots of dependency injection features for a fully code-generation based dependency injector.
AndroidAnnotations is an annotation-based framework for Android. It does have a limited dependency injection module (which is only a small subset of AA), however that is not its main feature. It adds annotation based, boilerplate removing APIs for lots of thing for Android, which are used in every project and normally require an awful lot of unnecessary code, like view and resource injection, event handling, instance state restoration, threading, etc. You can see all the use cases of AA here.
Dagger and AA can coexist, actually it really makes sense to use the sophisticated dep injection from Dagger and the lot of features of AA together (i do in all of my projects).
Disclaimer: i am an AndroidAnnotations developer.
recently I have created one sample application by implementing Dagger 2 and Android Architectural Components (Room and Viewmodel) which can help you understand dependency injection using dagger library along with MVVM architecture.
Here is the github project link

What is dagger exactly, and how it works [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I know this may be not the correct way to ask question but after reading lot and lot I am still confused about daggers and how it works and why we should use it. Since its been used in my current working project. Please somebody give me little hint in simple words what is the purpose of dagger will be very helpful.
Dagger is a compile-time JSR-330 dependency injection framework based on Java annotations.
What is dependency injection?
Dependency injection (sometimes termed Inversion of Control or IoC) is based on the idea that a given class should not need to know how to create or provide the classes it depends on. Providing those dependencies should be the responsibility of the class's user (or a separate class or factory).
For example, let's say you have class A that depends on class B, that depends on classes C and D. (In real terms, that might be an Application, that depends on a BusinessLogicClass, that depends on a Calculator and a Database.) It could look like this:
class A {
private B b = new B();
}
class B {
private C c = new C();
private D d = new D();
}
...but at that point it would be really hard to use a different C or D (calculator or database), even your B (business logic class) should work with a variety of data sources, or if you need to replace any of those pieces for unit testing. Dependency injection, as a concept, says that you should be able to pass in dependencies into the classes when you create them.
A a = new A(new B(new C(), new D())); // Now you get an A, but can replace any part of it.
What is a dependency injection framework?
A dependency injection framework automatically creates factories for all of your classes, so you can create an A without worrying about its dependencies, or its dependencies' dependencies.
A a = new AFactory().getA(); // Equivalent to the above, but easier!
Dependency injection frameworks usually come with a language for you to specify mappings, often called bindings, which is just a way of instructing that you should create a EImpl when a class asks for a EInterface or a FSubclass when a class asks for a FClass. This language also lets you choose when to create new instances: On every request, once across the whole app ("singleton"), or otherwise. Spring uses XML and Guice uses a custom Java class language for this; Dagger uses Java interfaces, classes, and annotations.
You can do dependency injection without a container or framework, but most of the time people think of a framework like Spring, Guice, or Dagger when you mention dependency injection. These frameworks automate away a lot of the new boilerplate you see above, which could otherwise make "manual" dependency injection hard to work with.
What about JSR 330?
Java standardized some interfaces and annotations as "JSR 330" to make it easier to switch between dependency injection frameworks, and to make it easy to write libraries that work in any framework. Like Spring and Guice, Dagger conforms to this standard.
Why is it a big deal that Dagger is compile-time?
Other dependency injection frameworks, including Spring and Guice, do their configuration at runtime: They use Java reflection to inspect classes' constructors, methods, and fields. This can be slow in production on servers and desktops, and is extremely slow on Android due to both VM differences and mobile processor/memory constraints. Consequently, teams at Square and Google wrote Dagger and Dagger 2 to use Java annotation processing to inspect the classes at compile time and automatically write standard Java code for plain Java objects to act like the factories above. Because this is plain Java without reflection, it can be much faster on Android and embedded systems, and can be optimized using existing tools.
Note, as well, that Dagger was written at Square by Bob Lee (who originally wrote Guice at Google); the Dagger 2 project is rewrite of Dagger maintained at Google that changes some of the specifics about how to configure Dagger and how to avoid using reflection. Both Dagger and Dagger 2 are annotation-based compile-time dependency injection frameworks for Java, but they're slightly different from one another.
What is dependency injection actually?
You will find a lot of technical contents about dependency injection but maximum time new learners find stuck to figure out the basic understanding of DI. Here is a real-life example of DI.
Importance of DI
Increase reusabilities of code
Good balance of loosely coupled dependancies
Ease to refactoring
Ease to test and debug
What is dagger?
Dagger is a DI framework that will generate a lot of boilerplate code for you to achieve the goal of dependency injection in Android development.
When to use dagger?
I got a clear vision of DI also with dagger from Android Dev Summit '19 session hopefully which will also clear your vision.

Does "Avoid dependency injection frameworks" in the Android Memory Guide apply to Dagger as well?

So I have come across this best practices on Android articles on memory performance.
http://developer.android.com/training/articles/memory.html
They said
Avoid dependency injection frameworks
Using a dependency injection framework such as Guice or RoboGuice may
be attractive because they can simplify the code you write and provide
an adaptive environment that's useful for testing and other
configuration changes. However, these frameworks tend to perform a lot
of process initialization by scanning your code for annotations, which
can require significant amounts of your code to be mapped into RAM
even though you don't need it. These mapped pages are allocated into
clean memory so Android can drop them, but that won't happen until the
pages have been left in memory for a long period of time.
But what about Dagger which they claim to be fast. Not sure which one should I go for?
This recommendation does not apply equally to all dependency injection frameworks.
..frameworks [that work like Guice] tend to perform a lot of process initialization by scanning your code for annotations, which can require significant amounts of your code to be mapped into RAM even though you don't need it..
Thus, if using a DI/IoC framework that doesn't scan for said [run-time] annotations, implying the [excessive] use of reflection, then this reason doesn't apply. While Dagger does use annotations these are used differently than by Guice1 and avoid the problem stated.
Since Dagger was written as "A fast dependency injector for Android and Java", the authors have designed it for this purpose and believe that it is suitable for such a target - go ahead, give it a try.
1 Dagger uses compile-time annotations (well, mostly) instead of relying on run-time annotations and reflection; it is the run-time annotation scanning and reflection that causes the issue the memory guide was warning about.
The Android team has recently updated their recommendation to suggest developers use Dagger 2.
The previous recommendation was based on the high cost of reflection. Since Dagger 2 no longer uses reflection - Dagger 1 did - they believe it "can be used in Android apps without needless runtime cost or memory usage".
(Disclaimer: I'm the Dagger 2 team manager.)
The creator of Dagger, #JakeWharton, also wrote a simpler view "injection" framework called Butterknife
because all the RoboGuice converts were complaining about lack of
"view injection" with Dagger.
You use it like this:
class ExampleActivity extends Activity {
#InjectView(R.id.title) TextView title;
#InjectView(R.id.subtitle) TextView subtitle;
#InjectView(R.id.footer) TextView footer;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.inject(this);
// TODO Use "injected" views...
}
}
Dependency injection best practices articles were recently added to Android developer official website. In these articles developers are encouraged to use Dagger 2 as a primary DI library for project medium (4-7 screens) and large (8+ screens) apps.
Dagger facilitates using DI in your app by creating and managing the graph of dependencies for you. It provides fully static and compile-time dependencies addressing many of the development and performance issues of reflection-based solutions such as Guice.

Transfuse vs AndroidAnnotations

I'd like to know if there's anyone using Transfuse and how it differs from Android Annotations. I mean the pros and cons of each one, and if there are other options besides these two.
Thanks.
I may not count because I wrote the library, but I am an active user of Transfuse :-)
Here's the comparison from Transfuse's point of view:
Transfuse and Android Annotations share the same goal of reducing boilerplate and complexity in Android. Both Transfuse and Android Annotations are extremely performant as they use nearly identical techniques for generating code at compile time. In fact AA was one of many inspirations for Transfuse.
Android Annotations battles boilerplate by introducing code in the class extensions associated with the annotated classes. You can find the introduced code in the Class_ files in the generated source. Android Annotations includes a variety of features including a light dependency injection mechanism, a REST client generator, and a variety of Activity/Context enhancements among others.
Transfuse, on the other hand, approaches this goal through Dependency Injection, POJO components and Manifest Management among other ideas borrowed from Enterprise Java libraries. For instance, Transfuse Activities don't extend android.app.Activity. Instead you add functionality to your Activities via the annotations, which Transfuse uses to wire up the resulting generated code. Transfuse is also JSR330 compliant, which means it is a fully featured IOC/DI engine comparable with Guice (Roboguice) or Dagger. This gives the developer a lot of functionality to wire up object graphs behind the application without having to maintain the resulting code. Finally, one my my favorite features, Transfuse manages the writing of the AndroidManifest.xml file for you, so you don't have to remember to register your components. This is a huge time saver, especially when starting a new application.
I am asked this comparison question a fair amount, or how it compares with RoboGuice and Dagger. I should probably put together a comparison matrix to highlight the significant differences between the libraries.

Categories

Resources