API design between modules

Learn API design between Android Gradle modules in Kotlin: internal by default, explicit API mode, api vs implementation and binary compatibility checks. About 25 minutes.

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 api when it should be implementation lets 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.

ConceptWhat it controlsWhere
internalModule-level visibilityKotlin source
Explicit API modePublic declarations must be marked on purposekotlin { explicitApi() }
api vs implementationWhether consumers can compile against a dependencydependencies { } block
ABI dump and checkPublic API changes are visible and reviewed.api file in the repo, CI
api/impl module splitConsumers see contracts, not implementationsModule 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 helpers internal or private unless another module needs them.
  • internal is checked by the Kotlin compiler only. In bytecode it is public (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 explicit public modifier and on public API without explicit types. explicitApiWarning() reports warnings instead, useful during adoption.
  • api exposes a dependency to consumers at compile time; implementation hides it. Use api only when your public signatures use that dependency's types.
  • api vs implementation does not change APK size. It changes what consumers can compile against and how far recompilation spreads.
  • binary-compatibility-validator: run apiDump and commit the .api file; apiCheck (part of check) 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 checkKotlinAbi and updateKotlinAbi. 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 internal and create them through DI or a factory.
  • Adding a subtype to a public sealed type breaks consumers' exhaustive when expressions 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(), forgetting public or internal on 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 bind OkHttpPaymentProcessor to PaymentProcessor with @Binds in this module instead.
  • Overrides such as charge in 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 leaked api dependency spread through the app
  • A :core:network module declared OkHttp and Retrofit as api instead of implementation.
  • 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.
The fix
  • Changed the dependencies to implementation and fixed the compile errors in feature modules by routing them through :core:network's own interfaces.
  • Kept api only for types that appear in :core:network's public signatures.
  • Checked ./gradlew :feature:profile:dependencies --configuration releaseCompileClasspath to confirm OkHttp no longer appeared on feature compile classpaths.
Accidental API exposure after a refactor
  • A developer made a UserRepositoryImpl class public to make a test easier.
  • Two feature modules started using the concrete class instead of the UserRepository interface.
  • A later refactor of the implementation broke both modules, and nobody had noticed the visibility change in review.
The fix
  • Added binary-compatibility-validator to the module and committed the .api file, so any public API change shows up as a diff and apiCheck fails 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 api when implementation is enough. Consumers can start using the library directly, and its changes recompile more modules. Use api only for types in your public signatures.
  • Relying on the default public visibility. Helper classes leak into the API silently. Enable explicit API mode in library-style modules, starting with explicitApiWarning() 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 .api file and run the check on every pull request.
  • Treating internal as 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

  1. Pick a library module in your project, for example :core:utils.
  2. Add kotlin { explicitApi() } to its build.gradle.kts (or explicitApiWarning() first if it has many declarations).
  3. Run ./gradlew :core:utils:compileDebugKotlin and fix each error: add public only to what other modules use, and make the rest internal or private.
  4. 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 in libs.versions.toml).
  5. Run ./gradlew :core:utils:apiDump and commit the generated file under core/utils/api/.
  6. Add a new public function, run ./gradlew :core:utils:apiCheck, and confirm it fails. Run apiDump again and look at the diff.
  7. Run ./gradlew :app:assembleDebug to 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.

Next: Managing tech debt and migrations