Clean architecture without the dogma

Learn clean architecture on Android as trade-offs: when the domain layer and use cases pay off, when to skip them, and how Google's layers differ. About 25 minutes.

Why it matters

  • In senior Android interviews, "when would you skip the domain layer?" separates candidates who memorise clean architecture diagrams from those who reason about trade-offs.
  • Adding a domain layer, a use case and extra mappers to a three-toggle settings screen adds files, indirection and review time without making anything easier to test.
  • Google's app architecture guide and "Uncle Bob" Clean Architecture disagree on some points (which way the domain and data layers depend on each other, whether repositories need interfaces). Knowing both lets you explain the choice your codebase made.
  • The ideas that do pay off almost everywhere are small: a ViewModel that does not talk to Retrofit or Room directly, dependencies passed in through constructors, and fakes in tests.

The simple explanation

  • A kitchen has a prep station, a stove and a pass. For a sandwich you skip the prep station and plate it directly.
  • For a ten-course menu, the prep station keeps the shared work (sauces, stocks) in one place so every dish uses the same recipe.
  • The prep station (domain layer) is optional; the stove and the pass (data and UI) are always there.
  • Building a prep station for one sandwich is dogma, not architecture.

Do you need clean architecture on Android? Not in its full form. Google's app architecture guide recommends a UI layer (Compose or views plus ViewModels) and a data layer (repositories and data sources) for every app, and an optional domain layer (use cases) between them. The guide says to add the domain layer when it helps: to hold complex business logic, or logic that several ViewModels reuse.

Two ways of drawing the dependencies are common, and both are valid:

  • Google's layered approach. UI depends on domain, domain depends on data. Use cases call repositories directly, and repositories are often plain classes. The UI may also call a repository directly when there is no use case worth writing.
  • Clean Architecture's dependency rule. Source code dependencies point inward, toward the business rules. The domain declares a UserRepository interface and the data layer implements it (dependency inversion), so the domain module depends on nothing.

The second gives a domain that compiles without any data library, at the cost of an interface and a binding for every repository. The first has fewer files, and you can still extract an interface for one repository when you need a second implementation or a fake.

When to skip the domain layer:

  • The screen mostly shows and edits data (list, detail, settings toggles) with little logic.
  • A rule is used by one ViewModel only and is easy to test there.
  • The use case would just call one repository method and return the result.

When to add it:

  • Several ViewModels need the same rule (pricing, eligibility, formatting).
  • One operation combines several repositories and the combining logic is non-trivial.
  • The ViewModel has grown hard to read because business rules are mixed with UI state handling.
LayerContainsSkip when
UIComposables, ViewModels, UI stateNever
DomainUse cases, sometimes domain modelsLogic is simple or used by one screen
DataRepositories, data sourcesNever

In a multi-module project the domain code often lives in a :core:domain module. With Google's approach it depends on :core:data; with the dependency rule it depends on nothing and :core:data depends on it. Either way, core modules never depend on feature modules.

The cost of a layer is real: more files, more mapping, and more places to look when you debug. The senior move is to add a use case when there is logic to put in it, often when a second screen needs the same rule, not speculatively.

Two layers always, one optional
Android app layers Layer stack of an Android app: UI elements and state holders form the UI layer, an optional domain layer of use cases sits in the middle, and repositories and data sources form the data layer; each layer depends on the one below it. DEPENDS ON 01 UI elements Composables or Views @Composable 02 State holders ViewModels, UI state StateFlow<UiState> 03 Domain layer · optional use cases for shared rules GetFeedUseCase 04 Repositories one source of truth per data FeedRepository 05 Data sources Room, Retrofit, DataStore FeedDao UI LAYER DOMAIN DATA LAYER Dependency rule variant: the domain declares the repository interface and the data layer implements it, so the domain depends on nothing.
UI and data layers are in every app. Add the domain layer only when there is real logic to share.

Notes

  • Google's app architecture guide marks the domain layer as optional. The UI and data layers are recommended for every Android app.
  • Clean Architecture's dependency rule says source code dependencies point inward toward business rules. Google's guide lets the domain layer depend on the data layer. Pick one per codebase and be consistent.
  • A repository interface is worth it when you need a second implementation or a fake in tests. A repository used in one place with a real class is also fine; Kotlin makes extracting an interface later cheap.
  • Skip the domain layer when business rules are few and only one screen uses them. A one-line pass-through use case is noise.
  • Add use cases when several ViewModels share a rule, or when one operation coordinates several repositories.
  • Core modules never depend on feature modules, and feature modules should not depend on each other. Shared types go in a core module.
  • In Gradle, prefer implementation over api so a module does not expose its own dependencies to its consumers.
  • Test a ViewModel with a fake repository (or fake use case) that returns fixed data. Repository tests can use a fake API, an in-memory Room database or MockWebServer.
  • Too many Gradle modules or layers slow builds and onboarding. Match the structure to the size of the app and the team.
  • Google's guidance is one repository per type of data. A single repository for every entity in the app becomes a god class; split by data type (UserRepository, OrderRepository).

Code example

This shows the layers with a UserRepository interface in Clean Architecture style. The ViewModel depends on the interface, a network class implements it in production, and a fake implements it in tests.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.IOException
import retrofit2.HttpException
import retrofit2.http.GET
import retrofit2.http.Path
 
// --- Domain (or the data layer's public API, in Google's style) ---
data class User(val id: String, val name: String)
 
interface UserRepository {
    suspend fun getUser(id: String): User
}
 
// --- Data layer ---
data class UserDto(val id: String, val name: String)
 
interface UserApi {
    @GET("users/{id}")
    suspend fun fetch(@Path("id") id: String): UserDto
}
 
class NetworkUserRepository(
    private val api: UserApi,
) : UserRepository {
    override suspend fun getUser(id: String): User = api.fetch(id).toDomain()
}
 
fun UserDto.toDomain(): User = User(id = id, name = name)
 
// --- UI layer: the ViewModel only knows the interface ---
sealed interface UserUiState {
    data object Loading : UserUiState
    data class Loaded(val user: User) : UserUiState
    data object Error : UserUiState
}
 
class UserViewModel(
    private val repo: UserRepository,
) : ViewModel() {
    private val _state = MutableStateFlow<UserUiState>(UserUiState.Loading)
    val state: StateFlow<UserUiState> = _state.asStateFlow()
 
    fun load(id: String) {
        viewModelScope.launch {
            _state.value = try {
                UserUiState.Loaded(repo.getUser(id))
            } catch (e: IOException) {
                UserUiState.Error // no connection
            } catch (e: HttpException) {
                UserUiState.Error // non-2xx response
            }
        }
    }
}
 
// --- Test double: no network, no Robolectric ---
class FakeUserRepository : UserRepository {
    override suspend fun getUser(id: String): User = User(id, "Test User")
}
  • UserViewModel takes UserRepository, so production code passes NetworkUserRepository and tests pass FakeUserRepository.
  • There is no use case: the ViewModel calls the repository directly because there is no business rule to put in one.
  • toDomain() keeps the network shape (UserDto) out of the UI. When the two shapes are identical and the API is stable, some teams skip this mapping; it pays off once they start to differ.
  • The Retrofit suspend call is already main-safe, so load needs no withContext.
  • In a test, viewModelScope uses Dispatchers.Main, so set a test dispatcher with Dispatchers.setMain first.

Run the idea in plain Kotlin

The same ViewModel logic, without Android: a class that depends on a UserRepository interface, run once with a "network" implementation and once with a fake.

import kotlinx.coroutines.*

data class User(val id: String, val name: String)

interface UserRepository {
  suspend fun getUser(id: String): User
}

class NetworkUserRepository : UserRepository {
  override suspend fun getUser(id: String): User {
      delay(100) // stands in for a network call
      if (id == "404") throw java.io.IOException("not found")
      return User(id, "Server user " + id)
  }
}

class FakeUserRepository : UserRepository {
  override suspend fun getUser(id: String): User = User(id, "Test User")
}

// Plays the ViewModel: knows only the interface
class UserPresenter(private val repo: UserRepository) {
  suspend fun load(id: String): String =
      try {
          "Loaded " + repo.getUser(id).name
      } catch (e: java.io.IOException) {
          "Error: " + e.message
      }
}

fun main() = runBlocking {
  val prod = UserPresenter(NetworkUserRepository())
  val test = UserPresenter(FakeUserRepository())

  println("prod: " + prod.load("7"))
  println("prod: " + prod.load("404"))
  println("test: " + test.load("7"))
}

Expected output:

prod: Loaded Server user 7
prod: Error: not found
test: Loaded Test User

In production

Domain layer on a three-toggle settings screen
  • A team added a use case, a domain model and a mapper to a settings screen with three boolean toggles stored in DataStore.
  • Reviewers had to read three extra files to approve a small change.
  • Each use case was a one-line pass-through: it called one repository method and returned the result.
  • New team members asked why a toggle needed a use case, and copied the pattern into other simple screens.
The fix
  • The team removed the pass-through use cases; the ViewModel called the settings repository directly.
  • They wrote the rule down in the architecture notes: add a use case when it holds logic or when two ViewModels share it.
  • They kept the domain layer for the onboarding flow, whose eligibility rules were shared by two screens.
Circular dependency between feature modules
  • feature:settings already depended on feature:profile to show a profile header.
  • A developer then made feature:profile depend on feature:settings to reuse a UserPreferences type.
  • Gradle refused to build because the two projects now depended on each other, and nothing caught the first feature-to-feature dependency earlier.
The fix
  • They moved UserPreferences and the shared header into core modules (:core:model, :core:ui) that both features depend on.
  • Both feature-to-feature dependencies were removed; navigation between the two screens is wired in the app module.
  • They added a CI check that fails when any :feature:* module declares a dependency on another :feature:* module, so the first such edge is caught, not just the cycle.

Common mistakes

  • A use case for every repository call. A use case that only forwards to one repository method adds a file and a hop with no logic. Call the repository from the ViewModel until there is a rule worth extracting.
  • Data sources in the ViewModel. Calling Retrofit or a Room DAO from a ViewModel spreads caching and mapping rules across screens. The ViewModel should depend on a repository (or a use case).
  • Treating one diagram as the law. Insisting on an interface, a mapper and a use case for every type, even when the codebase follows Google's simpler layering, adds cost without benefit. Choose a style deliberately and apply it consistently.
  • Feature-to-feature dependency. If feature:profile imports a type from feature:settings, the two features are coupled and a cycle is one import away. Move shared types to a core module.
  • Too many Gradle modules too early. Splitting a small app into dozens of modules adds build configuration and wiring that a small team pays for every day. Split when ownership or build times call for it.
  • God repository. One repository with methods for every entity is hard to change and test. Split by type of data (UserRepository, OrderRepository).

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“When would you skip the domain layer in an Android app?”

“How does Google's recommended architecture differ from Uncle Bob's Clean Architecture?”

“What is the difference between a use case and a repository method?”

“How do you test a ViewModel that calls a repository?”

Quiz

Which layer does Google's app architecture guide describe as optional?

What is the main benefit of passing a repository interface into a ViewModel's constructor?

When is a use case NOT worth adding?

In a multi-module Android project, which dependency is allowed?

0 of 4 answered

Mini task

Refactor a ViewModel to use a repository interface (15 min)

  1. Create a UserRepository interface with suspend fun getUser(id: String): User and a data class User(val id: String, val name: String).
  2. Create NetworkUserRepository that implements UserRepository and calls a Retrofit UserApi (you can leave the real network call untested).
  3. Change UserViewModel to take UserRepository in its constructor instead of NetworkUserRepository. Expose a StateFlow<UserUiState>.
  4. Create FakeUserRepository that implements UserRepository and returns a fixed User("1", "Test").
  5. Write a unit test: call Dispatchers.setMain(StandardTestDispatcher()) in setup, create the ViewModel with FakeUserRepository, call load("1") inside runTest, call advanceUntilIdle(), and assert the state is Loaded with name "Test". Call Dispatchers.resetMain() in teardown.
  6. Decide whether this feature needs a use case. Write one sentence in the PR description explaining the choice.

Done when: the test passes with no network call, no Robolectric and no Android runtime, and the ViewModel constructor takes an interface, not a concrete class.

Next: Domain layer and use cases