Modularization strategies
Why it matters
- In a single-module Android app, every change rebuilds one large module and Gradle cannot work on parts of it in parallel. Splitting into feature and core modules lets Gradle build modules in parallel, reuse cached outputs, and skip modules a change cannot affect.
- Senior interviewers ask you to draw the module dependency graph and explain
apivsimplementationin Gradle, and what an api/implementation module split buys you, not just "use modules". - Without clear boundaries, a feature module can reach into another feature's internals, or see Retrofit and Room types it should not use. Modules with
internalclasses make the compiler enforce those boundaries. - Modules are not free: each one adds a build file, configuration time and DI wiring. Google's modularization guide warns that modules that are too fine-grained add build overhead and boilerplate.
The simple explanation
- A hospital has a public reception desk for each department (api modules) and the wards behind it (implementation modules).
- Patients and other departments talk to the reception desk; they never walk into a ward.
- The hospital director (the app module) knows every department and assigns the staff.
- A ward can reorganise its beds without anyone outside noticing.
- Adding a separate reception desk for every single doctor just adds hallways.
What is modularization in Android? It is splitting one app module into several Gradle modules with clear responsibilities and one-way dependencies. Google's modularization guide describes these common module types:
- App module: the entry point. It depends on the feature modules, sets up the
NavHost, and is where Hilt builds the dependency graph. - Feature modules: one feature or user journey each (screens, ViewModels). For example
:feature:profile. - Data modules: repositories and data sources for one type of data, for example
:core:data. - Core (common) modules: code many modules share, such as
:core:ui(design system),:core:network,:core:model.
The api/implementation split. When other modules need a contract but should not see how it is built, split it in two: an api module with interfaces and models (AuthRepository, Session), and an implementation module with the concrete classes (AuthRepositoryImpl, Retrofit, Room). Consumers depend on the api module only. The app module depends on the implementation module so DI can bind the real class. Google's guide calls this dependency inversion between modules.
| Module | Contains | Depends on |
|---|---|---|
:feature:profile | Profile screens and ViewModels | :api:auth, :core:ui |
:api:auth | AuthRepository interface, Session class | nothing (or :core:model) |
:impl:auth | AuthRepositoryImpl, Hilt binding | :api:auth, :core:network |
:core:ui | Design system components | Compose libraries |
:app | Application class, NavHost | feature modules, :impl:auth |
Dependencies point one way: from :app toward the core. No module depends on :app, core modules never depend on feature modules, and feature modules should not depend on each other.
Build-time benefit. With org.gradle.parallel=true, Gradle builds independent modules at the same time, and the build cache can reuse a module's output when its inputs did not change. Editing :feature:profile does not recompile :feature:settings. A change inside :impl:auth that does not change its public API does not recompile its consumers, because they compile against :api:auth.
Ownership benefit. A team can own :feature:checkout and keep its classes internal, so other teams cannot depend on its details.
Cost. Every module adds a build file, configuration time and wiring. Convention plugins in a build-logic included build keep the build files short, and a version catalog (libs.versions.toml) keeps library versions in one place. Google's guide warns against both extremes: modules so fine-grained that overhead dominates, and modules so coarse they become monoliths again.
Notes
- Common module types in Google's modularization guide: app, feature, data, core (common) and test modules.
api(project(":core:model"))exposes:core:modelto every module that depends on this one.implementation(...)keeps it private. Useapionly when this module's public classes or functions use that module's types.- Prefer
implementation. When a module's private dependency changes, consumers that only see it throughimplementationdo not need to recompile. apivsimplementationdoes not change what ends up in the APK; both are packaged at runtime. It changes what consumers can compile against and how much gets recompiled.- An api module holds interfaces and models and is usually small. Making it a plain Kotlin module when it needs nothing from Android keeps it fast to build, but it is not a rule.
- Mark classes in implementation and feature modules
internalunless another module needs them. That turns a boundary from a convention into a compile error. - With Hilt, the
@Module @InstallIn(SingletonComponent::class)that@Bindsthe implementation usually lives in the implementation module. The app module just depends on it so Hilt can find the binding. - No module may depend on
:app(an application module cannot be a dependency anyway). Shared code goes in a core module. - Feature-to-feature dependencies couple teams and invite cycles. If
:feature:checkoutneeds the current user, it depends on:api:auth. Navigation between features is wired in:app(see the navigation across modules lesson). - Start with a few modules and split when a team boundary or a measured build-time problem calls for it. Measure with a Build Scan (
--scan) or the Build Analyzer in Android Studio before and after. ./gradlew :feature:profile:dependencies --configuration releaseCompileClasspathshows exactly which modules a feature can compile against;:impl:authshould not be there.
Code example
This shows the api/implementation split as three modules: :api:auth with the interface, :impl:auth with the implementation and its Hilt binding, and :feature:profile, which sees only the interface.
// ===== :api:auth (build.gradle.kts: plugins { kotlin("jvm") }) =====
// src/main/kotlin/com/example/api/auth/AuthRepository.kt
package com.example.api.auth
import kotlinx.coroutines.flow.Flow
data class Session(val userId: String, val displayName: String)
interface AuthRepository {
val session: Flow<Session?>
suspend fun login(email: String, password: String): Result<Session>
suspend fun logout()
}// ===== :impl:auth (depends on :api:auth and :core:network) =====
// src/main/kotlin/com/example/impl/auth/AuthRepositoryImpl.kt
package com.example.impl.auth
import com.example.api.auth.AuthRepository
import com.example.api.auth.Session
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import retrofit2.http.Body
import retrofit2.http.POST
internal data class LoginRequest(val email: String, val password: String)
internal data class LoginResponse(val userId: String, val displayName: String)
internal interface AuthApi {
@POST("login")
suspend fun login(@Body request: LoginRequest): LoginResponse
}
@Singleton
internal class AuthRepositoryImpl @Inject constructor(
private val api: AuthApi,
) : AuthRepository {
private val current = MutableStateFlow<Session?>(null)
override val session: Flow<Session?> = current.asStateFlow()
override suspend fun login(email: String, password: String): Result<Session> =
try {
val response = api.login(LoginRequest(email, password))
val newSession = Session(response.userId, response.displayName)
current.value = newSession
Result.success(newSession)
} catch (e: IOException) {
Result.failure(e)
}
override suspend fun logout() {
current.value = null
}
}
@Module
@InstallIn(SingletonComponent::class)
internal abstract class AuthModule {
@Binds
abstract fun bindAuthRepository(impl: AuthRepositoryImpl): AuthRepository
}
// (A Retrofit @Provides for AuthApi would also live in this module.)// ===== :feature:profile (build.gradle.kts: implementation(project(":api:auth"))) =====
package com.example.feature.profile
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.api.auth.AuthRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
@HiltViewModel
class ProfileViewModel @Inject constructor(
auth: AuthRepository,
) : ViewModel() {
val greeting: StateFlow<String> = auth.session
.map { "Hello, " + (it?.displayName ?: "Guest") }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "Hello")
}:feature:profileimports onlycom.example.api.auth. BecauseAuthRepositoryImpl,AuthApiand the DTOs areinternalto:impl:auth, they could not be used from the feature even if someone added the dependency.- The Hilt binding lives next to the implementation.
:appdeclaresimplementation(project(":impl:auth")), and Hilt picks upAuthModulewhen it builds the graph. - Changing how login works inside
:impl:authdoes not change:api:auth, so:feature:profiledoes not recompile. - Real login code also handles
HttpExceptionand stores the session; it is trimmed here to keep the module structure visible.
Run the idea in plain Kotlin
Each "module" is modelled as a block of code: the feature only knows the interface from the api part, and the "app" decides which implementation to hand it.
// ---- api module: the contract ----
interface PaymentGateway {
fun charge(amountCents: Int): String
}
// ---- implementation module: hidden details ----
class CardGateway(private val merchantId: String) : PaymentGateway {
override fun charge(amountCents: Int): String =
"Charged " + amountCents + " cents for merchant " + merchantId
}
// ---- test fixtures ----
class FakeGateway : PaymentGateway {
val charges = mutableListOf<Int>()
override fun charge(amountCents: Int): String {
charges += amountCents
return "Fake charge " + amountCents + " (no network)"
}
}
// ---- feature module: depends only on the api ----
class CheckoutFeature(private val gateway: PaymentGateway) {
fun pay(amountCents: Int): String =
if (amountCents <= 0) "Nothing to pay" else gateway.charge(amountCents)
}
// ---- app module: the composition root ----
fun main() {
val checkout = CheckoutFeature(CardGateway("shop-42"))
println("App: " + checkout.pay(5000))
val fake = FakeGateway()
val testCheckout = CheckoutFeature(fake)
println("Test: " + testCheckout.pay(5000))
println("Test: " + testCheckout.pay(0))
println("Fake recorded: " + fake.charges)
}Expected output:
App: Charged 5000 cents for merchant shop-42
Test: Fake charge 5000 (no network)
Test: Nothing to pay
Fake recorded: [5000]
In production
- Over a year, a team created a new Gradle module for almost every screen, each with its own copied build file.
- Sync and configuration time grew with every module, and one change to a shared build setting meant editing dozens of files.
:core:uiexposed many libraries withapi(...), so a small change in one of them recompiled most of the project.
- They measured first with Build Scans to see where time went (configuration, compilation, or tasks that were not cached).
- Screens that always changed together were merged into feature modules by user journey (auth, checkout, settings).
- Copied build files were replaced with convention plugins in
build-logic. :core:uiswitched toimplementationfor libraries its public API did not use, so changes stayed local.
:feature:checkoutdepended on:feature:authto read the current user, and later:feature:authneeded the cart count from:feature:checkoutfor a badge.- Gradle refused to build the cycle. The quick fix was to merge both into a shared
:feature:commonmodule, which kept growing. - Every change to the cart badge recompiled the auth screens and the other way round.
- They extracted
AuthRepositoryinto:api:authandCartRepositoryinto:api:cart, with implementations in:impl:authand:impl:cart. - Each feature now depends only on the api modules it needs, never on another feature.
:appdepends on both implementation modules so Hilt can bind them, and the cycle is gone.
Common mistakes
- Putting shared code in the app module. Feature modules cannot depend on
:app, so shared code there is unreachable or gets copied. Move it to a core module. - Using
implementationwhen the public API needsapi. If:core:datahas a public function that returns a type from:core:modelbut declares it withimplementation, modules that call that function will not compile until they add:core:modelthemselves. Useapiwhen the type appears in public signatures. - Using
apieverywhere. Everyapidependency leaks into consumers' compile classpath, so changes to it recompile more modules. Default toimplementation. - A module per screen. Very fine-grained modules add build files, configuration time and wiring. Group screens by feature or user journey.
- Feature-to-feature dependencies.
:feature:checkoutdepending on:feature:authcouples two teams and invites cycles. Depend on an api module, and wire navigation in:app. - Splitting without measuring. Modularizing "for build speed" without a Build Scan or Build Analyzer baseline means you cannot tell whether it helped.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you structure a multi-module Android project?”
“What is the difference between api and implementation in Gradle?”
“When would you NOT add a new module?”
“How do you handle code shared by two feature modules?”
Quiz
A module declares api(project(":core:model")). What happens for a module that depends on it?
Which module usually depends on the implementation modules so Hilt can bind them?
:feature:checkout needs to read the current user. What should it depend on?
A team has many Gradle modules and builds feel slow. What should they do first?
0 of 4 answered
Mini task
Add an api/implementation split to an existing area (20 min)
- Find the public surface. In your auth code, list every class another module imports. Usually that is an
AuthRepositoryinterface and aSessionmodel. These go into:api:auth; everything else goes into:impl:auth. - Create the api module. Add
include(":api:auth")tosettings.gradle.kts, createapi/auth/build.gradle.ktswithplugins { kotlin("jvm") }(or your Kotlin library convention plugin), and move the interface and model toapi/auth/src/main/kotlin. - Create the implementation module. Add
include(":impl:auth"), make it an Android library, and addimplementation(project(":api:auth")). MoveAuthRepositoryImplthere, mark itinternal, and add a Hilt module that@Bindsit toAuthRepository. - Update consumers. In each feature module, replace the dependency on the old auth module with
implementation(project(":api:auth"))and fix imports. - Wire the app. In
app/build.gradle.kts, addimplementation(project(":impl:auth")). - Verify. Run
./gradlew :feature:profile:dependencies --configuration releaseCompileClasspathand confirm:impl:authis absent. Run./gradlew assembleDebug.
Done condition: feature modules compile against :api:auth only, AuthRepositoryImpl is internal to :impl:auth, and the app module is the only module that depends on :impl:auth.