Injection libraries for Java, Android: Butterknife & Roboguice



In this article, I will show you how to inject Android views using Roboguice and Butterknife, and how to use dependency injection using Roboguice. You can infer that Butterknife is not a dependency injection library.

Why do we need them?

If you start to develop programs beyond “hello world” with java or all other languages, you probably want to get rid of some repetitive, cumbersome boilerplate coding parts. Indeed, we should focus on logic, not on metaprogramming.

For example, in Android development, you get view references as follows:



In this code, we only want to change a textView’s text and show the labels of the two buttons. What we want is called our program’s logic. As it is obvious we have to write a lot of statements to achieve such a simple task. Now try to guess what happens if you have a lot of views, more than just two…

Butterknife helps us to focus on logic

With this library, it is easier for us to create view references. So you can write a shorter version of the above example with Butterknife like this:




It is needless to say that we can do the same task with less code. And less code is better code. But not too much less to sacrifice code readability.

For more information about Butterknife you can visit the pages below:
1. https://github.com/JakeWharton/butterknife
2. http://jakewharton.github.io/butterknife/

Roboguice has more than Butterknife does

So far, we've seen how to make view injection. We accessed views in a shorter way. But all the things we do is not accessing views. Most of the applications have more than a few views; probably some system services, classes, and objects will be required too.

Roboguice is here to strip away boilerplate code every application needs. For example, if you want to create a new android activity, it is mandatory to write a constructor method and specify which layout the activity will use.

Or it can inject system services as follows:

Wrapping up

If you are sick of referencing views, go use Butterknife. It will save considerable time in long run. If you want more, use Roboguice. But be aware of that there is a performance difference between these as Roboguice does it jobs in runtime whereas Butterknife does in compile time. It means Roboguice is the slower one. Butterknife does not have any performance impact.

1. http://java.dzone.com/articles/dependency-injection-roboguice
2. http://stackoverflow.com/questions/27180820/difference-between-roboguice-and-butter-knife-dependency-injection

Comments

Popular posts from this blog

Migrating from PHP to Python

Memory organization and cache management

(DRAFT) Scaling a django project using celery and elasticsearch