All about android application development

Effective Android — a guide for professional Android application development

If you are an Android developer who have worked on personal apps and you are now responsable for making a professional app, maybe you feel a bit lost in the galaxy of the Android development. There are indeed a lot of articles about architecture, libraries, good practices, testings, sample code…

In this article, I’m not gonna tell you how to create a project on Android Studio, nor how to create an Activity and communicate with it’s inner Fragment.

I will give you some Android development tips, allowing you to move to a more professional approach.

All of this is based on my experience. I’ve used this to build all the applications we are now producing in my company and we are doing quite well. I’m not pretending that it’s the only way to go. Nonetheless, if, you follow these tips you will be in the right path to build a great and S.O.L.I.D Android app.

You might think, is this will make things more complexe ? Why do I need to add architecture, principles, test, abstraction, to my code when it’s already a bit messy with all these Activities, Fragments, Layouts, build.config, gradle…

The only answer I could give is the ability to change, to adapt and to do it fast. In order to build the best product for your customer, the management will ask you to change the existing features, to add more, and to do that quickly. To do so, you might get more developers in the team, testers, and more and more people will be involved in the project. You will not be on your own, building your mobile app, and you need to be prepared.

Part 1 — General concerns

Item 1 — You need a proper architecture

When you start developing for Android, the sample code you will find everywhere are usually using Activities for everything. That’s fine, until you start developing in a professionnel environment.

Sticking everything in your Activity will make your code hard to read, hard to modify, not re-usable and you will of course break the first S.O.L.I.D principle…

I’m not gonna tell you how to architecture your app. There are already plenty of really good articles about the Android architecture. The best article you can checkout is this one : https://github.com/android10/Android-CleanArchitecture by @fernando_cejas

It will give you everything you need to start a new android project with a pretty nice and decoupled architecture. The main advantage of this architecture are the 3 modules. It separates the presentation (Activities, View, Fragment…) from the domain (domain model and business logic, with no Android dependencies) and the data (http call, database storage…).

Maybe, if you see this architecture for the first time, there is a lot to take.

The most important thing here, is that you now have an architecture. A good architecture will be your key to success. Every new developer getting involved on your project will see that you put some effort, building a nice and tidy piece of code. It will be easy for him/her to understand how things are related to each other. By simply looking at the list of use cases, anyone should get the purpose of your app and what features the user can use.

I’m not going to talk much more about this. I could cary on for hours. We’ve been using this architecture in my company for more than 3 years now. We have tested different variant of it, tweak it to use EventBus, Repository Pattern, View Model Binding… and the only thing I would recommend is to try it !

If, for any reason, you are not confortable about using RxJava, there is way to use the Android Clean Architecture project with Guava Event Bus and Executors instead of Rx. The only thing you will need to do is to implement a event caching strategy in order to retrieve your event on configuration change.

Item 2 — Do not re-invent the wheel

Libraries are not a good solution to solve problems. But, unless your company gives you unlimited time and budget to develop your Android app (in that case, where do I apply for a job?) you don’t want to re-write what’s already been written.

Читайте также:  Установщик драйверов для андроид

Almost every Android apps need a way to make http calls, parse xml or json data, store and retrieve data into a database, inject dependencies, manipulate views or use cached image loading.

All of these concerns as been tackled already, and there is bunch of great libraries, that have been widely tested, you could use. Here is a non exhaustive list of libraries you might want to look at before you start developing.

The only advice I could give you is to be careful when you choose a library. Many of them are great, but, not always maintained or documented. Choose them carefully and don’t forget to mention the author 🙂

Item 3 — Isolate Android from the rest of your app

Let’s be honest Android Context is a god object. It’s absolutely everywhere on Android. The Context object can be quite big and could be very dangerous for your app in terms of memory leak ( see Item 5 — don’t use AsyncTask).

This is one of the reason why, one of the first thing I would say to a new Android developer in the team is to abstract away the Android framework. It means that every time you want to use an Android class, consider using it hidden behind an interface.

By doing this, you will end up writing most of you code in pure java/kotlin, with no context hanging around, reducing the odds of retaining a reference to an old Context somewhere in your app.

Also, this will help make you app more responsive to changes and easy to test. Testing Android code can be painful, but if the Android framework is reduced to a simple UI display job, then most of your code will be easily testable. Finally, the presentation module can be tested using UI Test framework like Espresso.

Unit and integration test will be easy to create using JUnit and the Mocking framework of you choice (JMock, Mockito).

Item 4 — Observer Pattern

When you start developing on Android, you will find many sample code that create an AsyncTask in an Activity, make an http request, parse the result and then set some text on TextViews in order to display the result to the user. That’s ok, but on Android you could have dozens of user interactions in less then a minutes, and then, thing can get messy in your code when you want to respond to them based on the previous state…

This is when you want to implement a sort of Observer Pattern. You want your ui to react to user interactions, http responses, database updates without managing the different state you could be in manually.

This is called Reactive Programming. The best definition you can find comes from the reactive manifesto :

we want systems that are Responsive, Resilient, Elastic and Message Driven. We call these Reactive Systems. http://www.reactivemanifesto.org/

If you are not familiar with Reactive Programming, I’ll advise you to read this great article wrote by André Staltz https://gist.github.com/staltz/868e7e9bc2a7b8c1f754

They are many ways to create a reactive system. You can easily build your own by following the principle defined in the manifesto.

Let me give you some ideas you could follow in order to make your Android app act like a reactive system :

  • Responsive “The system responds in a timely manner if at all possible” : in order to archive this, your ui will need to respond to event at any time. The best approach here will be to subscribe to the events required and adjust the ui accordingly (using Rx for exemple)
  • Resilient “The system stays responsive in the face of failure” : This one can be treated easily using a clear separation between all the layers but also, by using view binding in order to display to the user the correct state of the view based on the event that come at any time.
  • Elastic: “ The system stays responsive under varying workload” : To make your app Elastic, you will need to clearly separate the front end (presentation) from the backend (domain, data). If the ui and the data fetching are clearly separated, your system will be easily scalable.
  • Message Driven: “ Reactive Systems rely on asynchronous message-passing to establish a boundary between components that ensures loose coupling, isolation and location transparency” : an event bus or Intents will help you do this combined with a clear architecture that separate the concerns. This could be done using BroadcastReceiver or Guava EventBus.
Читайте также:  Шашки для андроид для двоих

The other solution will be to use RxJava. It’s a great tool that will help you create a reactive system. It’s well designed and well documented, and it’s a great fit with the Android Clean Architecture. More informations can be found here : https://github.com/ReactiveX/RxAndroid

To conclude this part, I will advice that Activities and Fragment should not know where the data comes from. They should only reports user interactions to an object, and respond to messages they received in order to update the ui accordingly. That’s it. This is the first of the S.O.L.I.D principles. Single Responsibility. Activities and Fragment (or any other ui element) should be seen as simple, dummy views that are here to be the interface between you and the end user. They are not here to create http objects, or parse json files.

Single Responsibility Principle is fundamental to build maintainable and well architectured software.

Part 2 — Android

Item 5 — Use Gradle to automate your build process

The Android build process is very complex. There a lot of things to take care of in order to compile your APK, for Debug or Release purposes. Gradle is now the standard for Android build System, but many developers are unaware of its capacity.

Because Gradle is independant of AndroidStudio it also allows you to run the build process on a CI (Continuous Integration) server. And this is something you should definitely do.

Also, Gradle allows you to build different products flavors and builds types. It will make your life easier while building a debug version of your app and will allow you to have specific configurations for your release build.

You should take some time to learn how to use Gradle properly. You won’t regret it. The best reference is probably the book Gradle for Android by Kevin Pelgrims.

Item 6 — Don’t use Async Task for every http request

AsyncTask need to be used wisely. They could create memory leaks if you used them the wrong way.

This is something that have been really well documented by Dan Lew in his blog post The Hidden Pitfalls Of AsyncTask . I strongly advice you to read it.

AsyncTask, use the correct way, could be used when doing really short async processes. The task should take less than one or two seconds. Otherwise, there is a lot of alternative to AsyncTask you could use, like Java Executors and Runnable/FutureTask or RxJava and Schedulers.

Item 7 — Use a dependency injection system

According to the Microsoft ASP.net documentation, Dependency Injection is :

Dependency injection (DI) is a technique for achieving loose coupling between objects and their collaborators, or dependencies. Rather than directly instantiating collaborators, or using static references, the objects a class needs in order to perform its actions are provided to the class in some fashion. Most often, classes will declare their dependencies via their constructor, allowing them to follow the Explicit Dependencies Principle. This approach is known as “constructor injection”.

Constructor injection is a great way of architecture you class dependencies. It avoid creating new objects directly in your class, bounding it to that strong dependency.

Using Constructor dependency will give you more flexibility when it comes to change you dependency. By using interfaces in the constructor you will create a weak dependency and ease the changes in the implementation of that interface. You will have loose coupling between your objects and a modular code base architecture ! Ideal.

There are many ways to do this yourself. You could also use a dependency injection framework. Dagger 2 (formerly Square, now maintained by Google) is good one. It will allow you to create module, explicit the dependency between them, and reduce boilerplate code.

Читайте также:  Finder для андроид что это такое

As it’s an annotation bases framework, Dagger will allow you to inject dependency simply by using @Inject annotation in your class. This is something you should look at as you structure your project. It will set a clear definition of how you create objects in your application and force your developers to follow the same pattern.

And to quote Windows DI documentation :

When classes are designed with DI in mind, they are more loosely coupled because they do not have direct, hard-coded dependencies on their collaborators. This follows the Dependency Inversion Principle, which states that “high level modules should not depend on low level modules; both should depend on abstractions.” Instead of referencing specific implementations, classes request abstractions (typically interfaces ) which are provided to them when the class is constructed. Extracting dependencies into interfaces and providing implementations of these interfaces as parameters is also an example of the Strategy design pattern.

Item 8 — Write unit test and run them on a CI server

This one might seem obvious but for some people, writing test for an Android app is not a big concern. Why ? Because “an Android app is just a way to display data sent by the server and interact with the user. There is no need for tests…”. Someone actually told me that once.

I’ve seen apps going on the store without any test coverage. Where this is acceptable for personal project, professional application should be tested for many reasons.

First, it give you confidence when you are adding functionalities, because you can rely on some tests to verify that you haven’t broke an important feature.

It’s also a good way to document you code, so it’s easy for other developer to understand what you were trying to do while developing a new feature.

Lastly, having test allow you to release faster, as you application will have a bunch of common functionality covered but automation testing.

My advice is to at least try writing test for your application. Start with some simple class to test, and the move to more critical part of your project. It’s not a waist of your time. See it like an investment for a brighter future 🙂

Part 3 — To go further

I wont details the items below, they are quite self-explanatory. You will be able to find resources on the Internet about those concept. It’s good to have them in mind when building a professional Android app !

Annexe A — Use continuous integration to run unit test, lint, static code analysis, build new version, deploy on the store and more. Basically, every process that is part of your application development should be automatized.

Annexe B — Use common code formatting, this will help all the members of your team to understand the legacy code better. It will also be good for you in the future when you’ll have to debug a old code 😉

Annexe C — Use TDD, Pair Programming and Code Review, that is not always possible and some teams tends to no doing it for many reason. But, if there is something I can be sure of, is that Pair programming will be a great asset for you team as it will empowered the team spirit and it give the youngest developer the chance to learn faster and better.

Conclusion

A Professional Android application follows the same principles of any Professional Software development. If you haven’t read it yet, I strongly recomand you to read Clean Code by Robert C. Martin.

You have to think about the robustness of your code, the architecture you’ll use to give a good understanding of you intents and the think about maintainability.

To do so, you will have to invest time and put some extra efforts in the process.

Not everything in this article has to be applied in order to build a good application. The most important is to have those concepts in mind and try to applied them. Build the architecture you think it’s best for you and your company, choose the library you like and the technologies you are passionate about.

Источник

Оцените статью