tezvyn:

Android's Domain Layer: Your Business Logic's Home

AI-drafted, machine-checkedSource: developer.android.comadvanced
Android's Domain Layer: Your Business Logic's Home

The Domain Layer is an optional buffer between your UI and data layers, housing reusable business logic. Use it for complex logic or simple rules shared by multiple screens, keeping your ViewModels lean. The footgun is overusing it for every simple data fetch.

WHY IT EXISTS To prevent ViewModels from becoming bloated with business logic and to make that logic reusable across different parts of the app. It decouples core business rules from both the UI that displays the results and the data sources that provide the inputs, improving testability and maintainability.

THE MENTAL MODEL Think of the Domain Layer as a set of specialized, single-purpose tools. Your ViewModel is the worker on an assembly line. Instead of building a complex tool from scratch every time, the worker just grabs the right pre-built tool (a Use Case) from the toolbox (the Domain Layer) to do one specific job.

HOW IT WORKS This layer contains simple Kotlin or Java classes called "Use Cases" or "Interactors". Each Use Case should have a single public method, often using Kotlin's invoke operator so it can be called like a function. It coordinates data from one or more Repositories (from the Data Layer), performs its specific logic, and returns the result to the ViewModel (in the UI Layer). A Use Case is typically stateless and main-safe, meaning it can be called from the main thread without blocking it.

WHEN TO USE IT Use it for complex business logic that would otherwise clutter a ViewModel, such as combining data from multiple sources to determine a user's status. Also use it for any business logic, even simple rules, that needs to be reused by two or more ViewModels. This centralization makes the logic easier to test and maintain.

WHEN NOT TO USE IT Avoid creating a Domain Layer if your app's business logic is very simple, like just fetching and displaying data. The biggest footgun is creating a Use Case that just calls a single repository function without adding any logic; this is just a layer of indirection for no benefit. In these simple cases, the ViewModel can call the Repository directly.

ONE CANONICAL EXAMPLE A FormatDateUseCase could be responsible for formatting a timestamp into a user-facing string according to specific business rules, like showing "today", "yesterday", or "2 days ago". Multiple ViewModels across the app (e.g., in a chat screen and a profile screen) can inject and call this same Use Case, ensuring consistent date formatting everywhere without duplicating code.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.