Tuesday, September 17, 2013

Android Dependency Injection

Dependency injection is just good practice.  It makes your code more testable, decoupled, readable, and whole bunch of other good things.  I've been using a Unity IoC container for a project at work, using the PRISM framework for a WPF app, and it really has spoiled me.  When I need a service in a new class that I'm writing, I just put it into the constructor and the framework takes care of the rest.  Nice.

I'm not opposed to "poor man's DI", which is DI without a framework.  I watched a Greg Young talk recently where he basically said frameworks=magic=bad.  I tend to agree somewhat.

It turns out you can't do DI in Android development without a framework.  The core building blocks (Activities and Services) are new'd up by the Android framework.  You don't get a chance to inject your dependencies.  For example, when you send an Intent, you never really get the opportunity to inject any dependencies.

So I went shopping for a DI framework for Android.  My only criteria was that it had to cost exactly zero dollars:)

Everyone is hyping up Dagger, because it is faster when the app starts up.  I found it cumbersome, and went with RoboGuice.  Less friction for me to get it working.

Now, I need to look into how to mock these dependencies when I write my tests.  RoboElectric seems promising.  Mostly because anything using the Dalvik VM is painfully slow, and they claim to allow you to test using just the JVM locally.

I know it seems like I am focusing more on doing these "setup" tasks rather than just cowboying some code.  And it's true.  It gets frustrating for me too, because I want working software.  But this effort is more than just about working software, it's about learning and instituting good practices so that maybe I can gain velocity later.  We'll see!

No comments:

Post a Comment