API design between modules
Why it matters
- In a multi-module Android app, every public class in a module is something other modules can start depending on. A small public surface lets a team refactor its module without breaking anyone.
- Senior interviews ask how you stop accidental API exposure and how you notice a public API change in review, not just how you write a function.
- Declaring a dependency as
apiwhen it should beimplementationlets consumers start using that library directly, and every change to it recompiles more modules. - Tools such as Kotlin's explicit API mode, the binary-compatibility-validator plugin and Kotlin's built-in ABI validation turn "keep the API small" from a convention into a build check.
The simple explanation
- A module is a restaurant kitchen.
- The menu (public API) lists the dishes a diner can order.
- The kitchen layout, storage and chef notes (
internal) are not on the menu. - Reworking the kitchen does not affect diners as long as the menu stays the same.
- Explicit API mode is the rule that every note must be labelled "menu" or "kitchen only".
How do you design the API of an Android module? Decide what other modules really need, make only that public, and keep everything else internal or private. In Kotlin the default visibility is public, so without care every helper class becomes part of the module's API.
internal means visible inside the same Gradle module (the same compilation). Other Kotlin modules get a compile error if they reference it. On the JVM, internal declarations become public in bytecode, and internal functions and properties get mangled names, so Java code can still reach them. Treat internal as a compile-time boundary, not a security feature.
Explicit API mode (kotlin { explicitApi() }) makes the compiler report an error for any declaration that would be public without an explicit public modifier, and for public functions and properties without an explicit type. Making something public becomes a deliberate act you can see in review.
api vs implementation. api(libs.okhttp) puts OkHttp on the compile classpath of every module that depends on yours. implementation(libs.okhttp) keeps it on their runtime classpath only, so they cannot use its types. Use api only when your public signatures expose that library's types. Both end up in the APK; the choice affects what consumers can compile against and what recompiles.
Binary compatibility checks. JetBrains' binary-compatibility-validator plugin dumps the public API into a .api file. apiDump writes it, apiCheck (run by check) fails when the current API differs from the committed file. Newer Kotlin Gradle plugin versions also have built-in, experimental ABI validation (abiValidation, with checkKotlinAbi and updateKotlinAbi tasks). Either way, a public API change shows up as a diff in the pull request.
| Concept | What it controls | Where |
|---|---|---|
internal | Module-level visibility | Kotlin source |
| Explicit API mode | Public declarations must be marked on purpose | kotlin { explicitApi() } |
api vs implementation | Whether consumers can compile against a dependency | dependencies { } block |
| ABI dump and check | Public API changes are visible and reviewed | .api file in the repo, CI |
| api/impl module split | Consumers see contracts, not implementations | Module structure |
For large boundaries, use the api/implementation module split from the modularization lesson: consumers depend on a small :api module with interfaces and models, and only the app module depends on the :impl module that DI binds.
Notes
- Kotlin's default visibility is
public. Mark implementation classes and helpersinternalorprivateunless another module needs them. internalis checked by the Kotlin compiler only. In bytecode it ispublic(functions and properties get mangled names), so Java and reflection can still reach it.- Explicit API mode (
kotlin { explicitApi() }) errors on public declarations without an explicitpublicmodifier and on public API without explicit types.explicitApiWarning()reports warnings instead, useful during adoption. apiexposes a dependency to consumers at compile time;implementationhides it. Useapionly when your public signatures use that dependency's types.apivsimplementationdoes not change APK size. It changes what consumers can compile against and how far recompilation spreads.- binary-compatibility-validator: run
apiDumpand commit the.apifile;apiCheck(part ofcheck) fails when the public API changes without an updated dump. - Kotlin's built-in ABI validation in the Kotlin Gradle plugin is experimental and uses
checkKotlinAbiandupdateKotlinAbi. After AGP or Kotlin upgrades, confirm that your ABI check task still runs on Android library modules. - Expose interfaces, data classes and factory functions; keep implementation classes
internaland create them through DI or a factory. - Adding a subtype to a public sealed type breaks consumers' exhaustive
whenexpressions at compile time. That is safer than a silent missing branch, but it is still a breaking change. - Removing or changing a public declaration is a breaking change. Add the new API first, deprecate the old one with
@Deprecated(..., ReplaceWith(...)), migrate callers, then remove it.
Code example
A :core:payment module with a deliberately small public surface: a sealed result, a request type, an interface and a factory function. The implementation is internal.
// core/payment/build.gradle.kts
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
}
kotlin {
explicitApi()
}
dependencies {
implementation(libs.okhttp) // used only inside the module, hidden from consumers
}// core/payment/src/main/kotlin/com/example/core/payment/PaymentApi.kt
package com.example.core.payment
public sealed interface PaymentResult {
public data class Approved(val transactionId: String) : PaymentResult
public data class Declined(val reason: String) : PaymentResult
}
public data class PaymentRequest(
val amountCents: Long,
val cardToken: String,
)
public interface PaymentProcessor {
public suspend fun charge(request: PaymentRequest): PaymentResult
}
// Consumers get the interface; the concrete class stays internal.
public fun PaymentProcessor(gatewayUrl: String): PaymentProcessor =
OkHttpPaymentProcessor(gatewayUrl)
internal class OkHttpPaymentProcessor(
private val gatewayUrl: String,
) : PaymentProcessor {
override suspend fun charge(request: PaymentRequest): PaymentResult {
if (request.amountCents <= 0) return PaymentResult.Declined("Amount must be positive")
// The real OkHttp call to gatewayUrl goes here. OkHttp is an `implementation`
// dependency, so no OkHttp type appears in the public API.
return PaymentResult.Approved("txn-" + request.amountCents)
}
}- With
explicitApi(), forgettingpublicorinternalon a top-level declaration is a compile error, so nothing becomes public by accident. - The factory function named like the interface (
PaymentProcessor(...)) is a common Kotlin pattern that hides the implementation class; with Hilt you would bindOkHttpPaymentProcessortoPaymentProcessorwith@Bindsin this module instead. - Overrides such as
chargein the internal class need no modifier; their visibility comes from the interface. - OkHttp is
implementation: consumers cannot import OkHttp types through this module, and upgrading OkHttp does not change this module's API.
Run the idea in plain Kotlin
sealed interface PaymentResult {
data class Approved(val transactionId: String) : PaymentResult
data class Declined(val reason: String) : PaymentResult
}
data class PaymentRequest(val amountCents: Long, val cardToken: String)
interface PaymentProcessor {
fun charge(request: PaymentRequest): PaymentResult
}
// Hidden implementation: callers only ever see PaymentProcessor
private class FakeGatewayProcessor : PaymentProcessor {
override fun charge(request: PaymentRequest): PaymentResult {
if (request.amountCents <= 0) return PaymentResult.Declined("Amount must be positive")
if (request.cardToken.length != 16) return PaymentResult.Declined("Invalid card token")
return PaymentResult.Approved("txn-" + request.amountCents)
}
}
fun PaymentProcessor(): PaymentProcessor = FakeGatewayProcessor()
fun describe(result: PaymentResult): String = when (result) {
is PaymentResult.Approved -> "Approved: " + result.transactionId
is PaymentResult.Declined -> "Declined: " + result.reason
}
fun main() {
val processor: PaymentProcessor = PaymentProcessor()
val requests = listOf(
PaymentRequest(5000, "4111111111111111"),
PaymentRequest(-1, "4111111111111111"),
PaymentRequest(100, "short"),
)
for (request in requests) {
println(describe(processor.charge(request)))
}
}Expected output:
Approved: txn-5000
Declined: Amount must be positive
Declined: Invalid card token
In production
- A
:core:networkmodule declared OkHttp and Retrofit asapiinstead ofimplementation. - Feature modules started importing OkHttp and Retrofit types directly, because they were on their compile classpath.
- When the team wanted to replace the HTTP stack inside
:core:network, dozens of feature modules had to change, and every OkHttp bump recompiled most of the app.
- Changed the dependencies to
implementationand fixed the compile errors in feature modules by routing them through:core:network's own interfaces. - Kept
apionly for types that appear in:core:network's public signatures. - Checked
./gradlew :feature:profile:dependencies --configuration releaseCompileClasspathto confirm OkHttp no longer appeared on feature compile classpaths.
- A developer made a
UserRepositoryImplclass public to make a test easier. - Two feature modules started using the concrete class instead of the
UserRepositoryinterface. - A later refactor of the implementation broke both modules, and nobody had noticed the visibility change in review.
- Added binary-compatibility-validator to the module and committed the
.apifile, so any public API change shows up as a diff andapiCheckfails until the dump is updated on purpose. - Enabled explicit API mode so every public declaration has to be written as
public. - Moved the feature modules back to the interface and kept the implementation
internal, testing it from inside its own module.
Common mistakes
- Exposing implementation classes instead of interfaces. Consumers bind to a concrete class, so any refactor breaks them. Expose an interface or factory and keep the class
internal. - Using
apiwhenimplementationis enough. Consumers can start using the library directly, and its changes recompile more modules. Useapionly for types in your public signatures. - Relying on the default
publicvisibility. Helper classes leak into the API silently. Enable explicit API mode in library-style modules, starting withexplicitApiWarning()if there are many errors. - Not checking the public API in CI. Without an ABI dump, a new public class or changed signature merges unnoticed. Commit the
.apifile and run the check on every pull request. - Treating
internalas security. It is a compile-time rule; Java and reflection can still reach internal code. - Removing a public API in one step. Callers break all at once. Deprecate with a
ReplaceWith, migrate callers, then remove.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you keep a Kotlin module's public API small?”
“What is the difference between api and implementation dependencies in Gradle?”
“How does Kotlin's internal visibility work at the JVM level?”
“How do you make a breaking change to a module that many teams use?”
Quiz
What does kotlin { explicitApi() } do in a Gradle module?
A module declares api(libs.okhttp). What does a module that depends on it get?
How is a Kotlin internal function represented in JVM bytecode?
What does binary-compatibility-validator's apiCheck task do?
0 of 4 answered
Mini task
- Pick a library module in your project, for example
:core:utils. - Add
kotlin { explicitApi() }to itsbuild.gradle.kts(orexplicitApiWarning()first if it has many declarations). - Run
./gradlew :core:utils:compileDebugKotlinand fix each error: addpubliconly to what other modules use, and make the restinternalorprivate. - Add the binary-compatibility-validator plugin to the module through the version catalog (
alias(libs.plugins.binary.compatibility.validator), with the current version from the plugin's README inlibs.versions.toml). - Run
./gradlew :core:utils:apiDumpand commit the generated file undercore/utils/api/. - Add a new
publicfunction, run./gradlew :core:utils:apiCheck, and confirm it fails. RunapiDumpagain and look at the diff. - Run
./gradlew :app:assembleDebugto confirm consumers still compile.
Done condition: the module compiles with explicit API mode, the .api file is committed, and apiCheck fails when you add a public declaration without updating the dump.