Large codebases cheat sheet
Key ideas
- Measure build time with
--scanor the Build Analyzer before changing any Gradle flag; blind optimization hides the real bottleneck. - Use lazy task APIs (
tasks.register,tasks.named,configureEach); eager APIs (tasks.create,tasks.getByName,tasks.all) configure tasks on every invocation. - The configuration cache skips the configuration phase when its inputs (build scripts,
gradle.properties, env vars, files read at config time) are unchanged; the build cache stores task outputs keyed by input hashes. - Convention plugins belong in an included
build-logicbuild, notbuildSrc, so only projects that use the changed subproject are rebuilt. - The version catalog at
gradle/libs.versions.tomlcentralizes versions; add a BOM withplatform(...)so artifact groups like Compose stay aligned. apivsimplementationcontrols compile-time visibility and recompile spread, not APK size; useapionly when a public signature exposes the dependency's types.- Enable
explicitApi()in library modules; expose interfaces, data classes, and factory functions, keep implementation classesinternal. - Guard public API with binary-compatibility-validator (
apiDump/apiCheck); after AGP or Kotlin upgrades confirm the ABI check still runs on Android library modules. - Migrate incrementally with the strangler pattern behind a remote-config flag; delete the old path only after the new path has run at 100 percent long enough to trust it.
- KSP replaces kapt for Room, Hilt, and Moshi by skipping Java stub generation, making annotation processing faster.
APIs at a glance
| API or term | Use it for |
|---|---|
tasks.register / tasks.named / configureEach | Lazy task creation and configuration; avoids configuring tasks that may never run |
@CacheableTask | Marks a custom task eligible for the local and remote build cache |
@Input / @InputFiles / @OutputFile / @OutputDirectory | Declare task inputs and outputs so Gradle can run up-to-date checks and cache outputs |
@PathSensitive(PathSensitivity.RELATIVE) | Prevents absolute file paths from polluting cache keys so CI outputs reuse on developer machines |
explicitApi() / explicitApiWarning() | Enforces explicit public modifiers and types in Kotlin library modules; start with warning mode during adoption |
binary-compatibility-validator (apiDump, apiCheck) | Commits a .api dump and fails CI when the public API changes without an updated dump |
@Deprecated with ReplaceWith | Deprecate an old API with an IDE quick-fix; raise level from WARNING to ERROR as migration finishes |
libs.versions.toml | Version catalog with [versions], [libraries], [bundles], [plugins] sections; one edit updates every module |
includeBuild("build-logic") | Includes a separate build for convention plugins so only affected projects rebuild on change |
platform(...) / BOM | Aligns versions of a group of artifacts, e.g. androidx.compose:compose-bom, so you declare artifacts without versions |
ComposeView / AndroidView | Interop hosts that let you move screens from XML to Compose one at a time |
checkKotlinAbi / updateKotlinAbi | Experimental Kotlin Gradle plugin ABI validation; confirm it still runs after AGP or Kotlin upgrades |
Snippets
Lazy vs eager task registration
@CacheableTask
abstract class GenerateBuildInfoTask : DefaultTask() {
@get:Input abstract val versionName: Property<String>
@get:OutputFile abstract val outputFile: RegularFileProperty
@TaskAction
fun generate() {
outputFile.get().asFile.writeText("versionName=${versionName.get()}\n")
}
}
// GOOD: lazy. The task is only created when something needs it.
tasks.register<GenerateBuildInfoTask>("generateBuildInfo") {
versionName.set("1.4.0")
outputFile.set(layout.buildDirectory.file("buildinfo/info.properties"))
}
// BAD: eager. Configured on every build, even ./gradlew help.
// tasks.create<GenerateBuildInfoTask>("generateBuildInfo") { ... }Version catalog entry
[versions]
androidGradlePlugin = "8.7.3"
kotlin = "2.1.0"
coreKtx = "1.15.0"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
[plugins]
android-library = { id = "com.android.library", version.ref = "androidGradlePlugin" }
myapp-android-library = { id = "myapp.android.library" }Strangler pattern: remote-flag factory
interface FeatureFlags { val useComposeProfile: Boolean }
class ProfileViewModel : ViewModel()
interface ProfileScreen { fun createView(context: Context): View }
class LegacyProfileScreen(private val viewModel: ProfileViewModel) : ProfileScreen {
override fun createView(context: Context): View =
LayoutInflater.from(context).inflate(R.layout.fragment_profile, null)
}
class ComposeProfileScreen(private val viewModel: ProfileViewModel) : ProfileScreen {
override fun createView(context: Context): View = ComposeView(context).apply {
setContent { Text("Profile") } // new Compose UI, hosted in the existing View tree
}
}
class ProfileScreenFactory(private val flags: FeatureFlags) {
fun create(viewModel: ProfileViewModel): ProfileScreen =
if (flags.useComposeProfile) ComposeProfileScreen(viewModel)
else LegacyProfileScreen(viewModel)
}Explicit API mode with hidden dependency
kotlin {
explicitApi()
}
dependencies {
implementation(libs.okhttp) // used only inside the module, hidden from consumers
}Rules of thumb
- Prefer
tasks.register,tasks.named, andconfigureEachovertasks.create,tasks.getByName, andtasks.all. - Never do IO (network calls, file reads) in the configuration phase; move that work into task actions.
- Prefer
implementationoverapiunless a public signature in your module exposes the dependency's types. - Never delete the old migration path until the new path has run at 100 percent long enough to trust it.
- Prefer small, composable convention plugins (library, application, Compose, Hilt, feature) over one plugin that configures everything.
- Never regenerate the lint baseline to silence CI; the baseline should only shrink as old violations are fixed.
Gotchas
- Using tasks.create instead of tasks.register. The task is created and configured on every Gradle invocation, even
./gradlew help, wasting time on tasks that never run. Switch to the lazytasks.registerAPI. - Absolute paths in task inputs. Machine-specific paths end up in cache keys, so a cache entry produced on CI never matches a developer machine. Annotate file inputs with
@PathSensitive(PathSensitivity.RELATIVE). - Treating internal as a security boundary.
internalis a Kotlin compile-time rule; in bytecode the declarations arepublicwith mangled names, so Java and reflection can still reach them. Do not rely on it to hide sensitive logic. - Adding Compose artifacts without the BOM. Each Compose artifact then needs its own version and they can drift apart. Add
platform("androidx.compose:compose-bom")and declare the artifacts without versions. - Removing a public API in one step. All callers break at once and the release is blocked. Add the new API first, deprecate the old one with
@DeprecatedandReplaceWith, migrate callers, then remove it. - Optimizing build flags without measuring. Turning flags on blindly hides the real bottleneck and can introduce subtle issues. Compare Build Scans or Build Analyzer reports before and after each change.
Quick interview answers
Why use tasks.register instead of tasks.create in a large Gradle build?
tasks.create configures the task eagerly on every Gradle invocation, even when the task never runs, which slows down every command. tasks.register is lazy: the task is created and configured only when something actually needs it.
What is the difference between api and implementation dependencies, and does it affect APK size?
api exposes a dependency to consumers at compile time; implementation hides it. It does not change APK size; it changes which modules can compile against the dependency and how far recompilation spreads when the dependency changes.
How do you migrate a screen from XML to Compose without a big-bang rewrite?
Use the strangler pattern: define a ProfileScreen interface with LegacyProfileScreen (ViewBinding) and ComposeProfileScreen (using ComposeView to host Compose inside the existing View tree). A factory reads a remote-config flag to pick the implementation, so you can roll back without shipping a new build.
What does the Gradle configuration cache do, and what are its inputs?
It stores the task graph and skips the configuration phase when its inputs have not changed. The inputs are build scripts, gradle.properties, environment variables, and any files read at configuration time.
How do you prevent accidental public API changes in a Kotlin library module?
Enable explicitApi() so the compiler errors on public declarations without an explicit public modifier and on public API without explicit types. Additionally, run binary-compatibility-validator's apiDump to commit a .api file and apiCheck in CI so any unrecorded public API change fails the build.
Why prefer KSP over kapt, and which libraries support it?
KSP skips the Java stub generation step that kapt performs for Kotlin sources, making annotation processing faster. Room, Hilt, and Moshi all support KSP, so you can migrate away from kapt.