Wednesday, September 12, 2012

WHY U NO USE ROBOGUICE!?!

That's exactly how I ask myself after trying out Roboguice 2 after a tutorial or two.

I discovered Roboguice after a guy in my facebook group posted a link to an excellent Android stack named android-bootstrap. Android-bootstrap is boilerplate application that includes tons of great open source tools and frameworks. I'll save this one for another time.

Back to Roboguice, roboguice adds dependency injection patterns to Android development. It adds annotations that makes writing Android applications like Spring apps in the J2EE space. It basically takes something that looks like this:

class AndroidWay extends Activity { 
    TextView name; 
    ImageView thumbnail; 
    LocationManager loc; 
    Drawable icon; 
    String myName; 

    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);
        name      = (TextView) findViewById(R.id.name); 
        thumbnail = (ImageView) findViewById(R.id.thumbnail); 
        loc       = (LocationManager) getSystemService(Activity.LOCATION_SERVICE); 
        icon      = getResources().getDrawable(R.drawable.icon); 
        myName    = getString(R.string.app_name); 
        name.setText( "Hello, " + myName ); 
    } 
} 

To something like this:

class RoboWay extends RoboActivity { 
    @InjectView(R.id.name)             TextView name; 
    @InjectView(R.id.thumbnail)        ImageView thumbnail; 
    @InjectResource(R.drawable.icon)   Drawable icon; 
    @InjectResource(R.string.app_name) String myName; 
    @Inject                            LocationManager loc; 

    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);
        name.setText( "Hello, " + myName ); 
    } 
} 

That's some kind of witchcraft if you ask me but still you can't argue how convenient this style of programming can be and we all know programmers are lazy as sin.