Creating testable code is one of the major aims when designing good, maintainable applications. I actually just started to take a look at developing for the Android and after playing a bit around with UI components, I started to develop a design that allows me to create a nicely testable Android app.
One of the major flaws in an untestable design is a very tight coupling between the view components and the actual model. This is often one of the issues why applications are hardly or even not testable at all. Btw, when I'm talking about testability, I consider writing automated unit tests of course. So my first approach was to see how to decouple this logic. MVC is a good tool for doing so.
When programming for the Android OS, you have roughly these three concepts:
- Activities
- Layouts
- Adapters
If you're familiar with J2ME programming, an Activity would probably mostly correspond to what is called a MIDlet there. It is a modular component which has a certain lifecycle and is most commonly but not necessarily associated to a single view (in the UI sense). Simply speaking they could be seen as UI views.
The UI part on Android is organized very nicely. All of the UI components can be written in a declarative way inside special XML files where the so-called "layouts" are being defined. From a conceptual point of view it has some similarities with XAML files used in WPF and Silverlight. This piece of XML code shows for instance an UI with vertically aligned buttons:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="0" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/button1"></Button>
<Button android:text="0" android:id="@+id/button2"
android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="0" android:id="@+id/button3"
android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
Such a declarative UI concept is very helpful when separating logic from the view.
The last thing are the adapters. They are basically the bridge between the model data and the UI layouts with its components. It's basically a data-binding mechanism which does already most of the job of synchronizing model data with what's being visualized on the UI. There are a couple of different adapters which are quite flexible and can be further customized by overriding them.
(Part 2: Writing testable code for the Android ยป)
(link will be activated as soon as that post goes online)
Questions? Thoughts? Hit me up
on Twitter