This series of articles will focus on practical approaches on how to write testable, re-usable and maintainable code when developing applications for Android.

Clean Android Code articles series:

In the first article I will be talking about why do we need to do it, will provide a list of libraries that I strongly recommend to use in your apps and will present a basic architecture of how things could be done, with not much specifics.

If you aren’t really interested in explanations and generic stuff — please proceed to the second article in the series, that will be more focused on pactical examples cleaning different parts of Android application

Why

Mobile applications, some years ago being small additions to a webpage with a relatively short development lifecycle, nowadays are standing much closer to a standalone desktop applications, that are being made by teams of multiple developers, designers and product managers. Applications become more and more complex, many more people are using them on every day basis.

This adds additional requirements to the modern app architecture — it needs to be robust and stable, extendable with as less effort as possible, able to change according to agile requirements, fast to incorporate new platform features and, at the same time, understandable to many different developers to ensure maintainability.

Having said all that, most of the talks and articles on the net are focusing on Clean Architecture, which is good and correct, but rarely provide practical examples on how to apply it on Android. Thus this series of articles.

Preparing the project

It would be crazy to write everything from scratch — after all, there are many years of industry experience behind, so let’s build on it.

Let’s first put some bullets on what good architecture should be:

Independent Testable Re-usable Extendable

To help us with all that, I suggest a following set of libraries and technologies. Let walk them one by one.

Kotlin — a buzz word recently. To put it shortly - a new language by Jetbrains, that is kinda like Java, but much easier to write in. Must have on Android.

Dagger 2 — a Dependency Injection(DI) library that is easy to use, has a huge community and does a good job.

RxJava + RxAndroid — Reactive Programming principles applied to Java. Not the only reactive library out there, but extremely popular. More on http://reactivex.io

Databinding — Even though it became stable only quite recently, it is already, to my opinion, and absolute must-have library in the project, that tremendously helps to remove UI boilerplate code

Retrofit + OkHttp — a set of libraries that, combined with Rx, will take off the pain of doing network requests and talking to REST APIs.

jUnit + Mockito(PowerMock) — good old jUnit for unit testing with a help of Mockito to do some mocking. For Kotlin we will also need PowerMock due to language specifics.

Jacoco — to measure your code test coverage, works great for Java, has some quirks for Kotlin

There are also some Android-specific libraries that may or may not be needed:

AppCompat with different other support dependencies, like RecyclerView

Google Play Services, if you need ads, maps, location and other stuff

Parceler(or any other similar library) to help deal with Parcelables

Glide (or Picasso) to help with lazy loading of images

Iconics to get rid of unnecessary images

Crashlytics(or anything similar) to know when things are crashing for your users

and others to your liking

Now that we have a set of libraries to help us, let’s get back to architecture.

Basic Architecture

There is one core principle that will help us to build a nice architecture — Testability. As soon you tell yourself that every single line of code should be covered by a properly written unit-test — your architecture starts building itself around properly tested units of code.

First let’s look at general clean architecture principles (SOLID):

Class should have a single reason to be changed (Single Responsibility principle) Classes should be possible to extend, but not modify from outside (Open/Closed principle) Layers of abstraction should let us replace parts and implementations (Liskov Substitution principle) Logic is separated via many interfaces rather then one big layer (Interface Segregation principle) Classes depend on abstractions, not implementations (Dependency Inversion principle)

All these are very nicely written principles, but where does it make us?

we write tests — and to make tests simpler we wouldn’t write a large class coupled with dependencies, right?

to make sure things are separated — we use interfaces applied via subscriptions, delegates, event busses, but at the same time we are careful to not make things too abstract

we construct our dependencies in one place and pass them to our classes — it helps keeping things up to date and change dependency implementation when necessary

There are several ways all these numbers and bullets were combined together on other platforms, most popular being Model-View-Controller(MVC), Model-View-Presenter(MVP), MVVM(Model-View-ViewModel). I won’t focus on these, because, in my opinion, it doesn’t really matter what you call your architectural approach, as long as code follows rules written above and it makes sense for your project and platform you work on.

Now, enough of theory, and let’s get to practice. Making good architecture on Android.

Good Android app architecture

On Android we have many things — activities, fragments, services, notifications, databases and others. With a general approach, everything is quite simple in the beginning, but as things grow more complex — activities and fragments become larger and larger, they incorporate lots of logic, talk to different web services and in the end it becomes very difficult to understand what’s going on by just looking at the code.

Following clean architecture principles, let’s imagine how could we structure things and assign responsibilities.

Activity & Fragment — these two would be only doing UI and glue different parts of the app together, after all these are screens that user will see, Views.

Somebody needs to do the logic for screens, like handling button clicks, doing analytics tracking, talking to network services. We could make a Controller, but on Android screens are created by the system, so we can’t really control them. That’s why need a Presenter. It’s job is to present things to the View.

The MVP’s Model in our architecture could be represented by Entities — these would some simple objects that we receive from our database or server. In Java they are called POJO(Plain Old Java Objects), because they don’t contain any logic, only fields.

Entities need to be retrieved, either from the database or the network, and we can call a thing that does that and keeps them in memory a Repository — something, who knows someone, who talks to the network/database.

By doing just that — View-Presenter-Model(Entity)-Repository we have already cleaned things a lot:

View would be tricky to unit test — it depends on things being displayed on the screen, so this we will have to skip

would be tricky to unit test — it depends on things being displayed on the screen, so this we will have to skip Presenter , on the other hand, only does the logic needed for the screen to work, and View always passes all it’s events to the Presenter by calling some method. And all this can be covered by unit tests

, on the other hand, only does the logic needed for the screen to work, and always passes all it’s events to the by calling some method. And all this can be covered by unit tests Entities have only fields and are completely dump, thus don’t need to be tested

have only fields and are completely dump, thus don’t need to be tested Repository can be a completely independent layer of our application not even knowing that UI(View) exists — it can be tested completely in isolation from other things

Nice. But I bet you already knew all this or could have read from other articles. Let’s get to the meat of things — cleaning things up with some real code.

Cleaning Android Code

From this point on I will be focusing on exact techniques you can use in the code to write a nice and clean Android application.

Article does not target junior developer audience, so it will be much easier for you to follow if you already know something about libraries that we plan to use: Kotlin, Gradle, Dagger2, Rx, Databinding and others.

You can allso follow external links to catch up with the most important things about libraries.

External links

Some external links that would help you get up to speed with libraries and patterns

Kotlin — You don’t need fancy articles to get into Kotlin, homepage has a very detailed and well-written documentation. Kotlin Reference will give you all the necessary information about how to write in Kotlin, and even will be able to try it out online. And if you want to gradually improve in Kotlin — try Kotlin Koans, it’s a series of exercises to help you better learn the language

The most important documentation for Dagger 2, I would say, is a talk by Jake Wharton on Devoxx

Future of DI with Dagger 2

If you want to get a little more technical, there is a another video

There also various articles, like Tasting Dagger 2 on Android by Fernando Cejas or Dependency Injection with Dagger 2 by CodePath, or Snorkeling with Dagger 2 by Konstantin Mikheev.

I have also written 4 small articles on Dagger 2 back when I was learning it: Dagger 2 for Android

For RxJava I would suggest to read Grokking RxJava by Dan Lew. RxMarbles will help you better understand operators, and ReactiveX has a very good documentation on how things work in Rx

With Databinding documentation will help a lot, and if you want to get some additional details, there is a very good talk published on Realm.io webpage — Marshmallow Brings Data Bindings to Android by Yigit Boyar and George Mount

Now, to the real stuff.

Clean Android Code articles series: