Links

Wednesday, February 6, 2013

Scala is better than injection framework

Android programming often drives me crazy, because I have to write too much to do a simple work. Hard to write is just a little problem when it is compared to poor maintainability. For example, let us see a typical Activity implementation:

The method onCreate is full of boilerplate code that makes maintaining painful. To reduce them, peoples thought about injection frameworks. Roboguice is one of them. It can improve the original code to the following way:

Although it seems to be much improved, there are some drawbacks in this approach:

Runtime performance

Wiring verbose XML layout

Not type-safe

If you make a mistake on the type of the view widget, your app will revenge you with a horrible runtime exception. Fortunately, Scala provides a much elegant solution. Here I show a direct translation of the example above to Scala language:

Lazy values replace injections, with no runtime performance degradation. And the code becomes much cleaner. However, this is not a final improvement. Another clutter that did not shown in this example is XML layout. It is too wordy to write a simple idea, and careful wiring with your code is mandatory. We can eliminate the source of the problem, by not writing layout in XML. The following example builds UI layout within an ordinary Scala code:

5 comments:

How about dealing with different scree sizes? Using xml layout, I could just create several layout folders and forget (partially :) ) about it (as described here: http://developer.android.com/training/basics/supporting-devices/screens.html). Using your approach, I'll need to check screen size manually.

As for runtime type checking in findViewById, in sbt-android-plugin you could create typed version of R (named TR) and then use it like following:

lazy val button = findView(TR.button)

It is better than find[TextView](R.id.name) but still require guessing on what Id should I use for current layout.

Thanks for a good suggestion. I revised the post to use typed resource (TR), and mentioned that the type-safety is its merit.

Because Scaloid layout is an ordinary Scala code, assigning different layout for each screen dimension is not too hard. However, it would be much better that the library support it systematically. Supporting multiple screens is one of the biggest issues of next version. I am thinking about a design like this: