Quality code: the benefits of using Android domain layer

Writing quality code: the benefits of using Android domain layer to write decoupled, testable and maintainable code.

Google in their Google I/O presented the architecture components for Android to develop application in a clean and reactive way. Many principles and layers are presented but we will focus on a specific optional one we’re using in our Android apps development, what they call the domain layer.
The domain layer sits between the data layer and the UI layer (ViewModels), and is responsible for encapsulating business logic so that it can be reused by multiple ViewModels.

It contains all the use cases (interfaces) and interactors (implementations) of the application. Each use case should have responsibility over a single functionality that can be reused by many ViewModels and they should not contain mutable data.

A use case is at the first sight only a wrapper of repository calls, so why we would use them instead of simply use repository calls in the ViewModels?

The purpose of the Use Cases is to request data to repositories and turn into something usable for the View. They can also be used to combine repositories: because the logic involves multiple repositories and can become complex, it’s possible to abstract the logic out of the ViewModel and make it more readable.

Use cases don’t have their own lifecycle. Instead, they’re scoped to the class that uses them. This means that you can call use cases from classes in the UI layer, from services, or from the Application class itself. Because use cases shouldn’t contain mutable data, you should create a new instance of a use case class every time you pass it as a dependency.

In the light of what we have seen, which are the main benefits of using a domain layer in the development of our application?
  1. ➡ It avoids code duplication, protecting the code from future changes
  2. ➡ It is easier to read Classes adopting domain layer
  3. ➡ It improves the testability of the app
  4. ➡ It avoids large classes by allowing you to split responsibilities

At Henesis, we have found that using the domain layer in our Android apps helps us create high-quality and easy-to-read code that is easier to maintain over time.