Managing tech debt and migrations

Learn to manage tech debt and Android migrations with the strangler pattern, feature flags, @Deprecated ReplaceWith, custom Lint checks and lint baselines. About 25 minutes.

Why it matters

  • Large Android codebases collect deprecated APIs, mixed architectures and legacy modules that slow down feature work and onboarding.
  • Interviewers ask how you would move hundreds of XML screens to Jetpack Compose without stopping feature work. The expected answer is an incremental migration (the strangler pattern) with feature flags, not a big-bang rewrite.
  • Migrations without a rollback switch and without a check that blocks the old API tend to stall half-done and regress as new code copies old patterns.
  • Senior engineers are expected to make debt visible, prioritise it by its cost to the team, and measure migration progress.

The simple explanation

  • You are renovating a building while people still live in it.
  • You cannot close it for two years, so you renovate one floor at a time.
  • A switch at each floor's entrance decides whether tenants use the old or the new floor (the feature flag).
  • Old pipes stay connected until the new ones have carried water for a while.
  • A sign on the wall bans installing any more old pipes (the Lint check).

How do you manage a large migration in an Android codebase? Replace the old system piece by piece while the app keeps shipping. The strangler pattern (named by Martin Fowler after the strangler fig) puts a seam in front of the legacy code: an interface, a factory or a navigation entry point. A new implementation grows behind that seam, a feature flag decides which one runs, and once the new path has proven itself in production you delete the old one.

For XML to Compose, the seam can be a screen: the new screen is a @Composable hosted in a ComposeView (or reached through a new navigation destination), and a remote flag picks the old or new screen.

Stop the bleeding. While you migrate, new code must not add more of the old pattern:

  • @Deprecated("Use loadUser()", ReplaceWith("loadUser(id)")) warns at every call site and gives the IDE a quick fix. Raise level to DeprecationLevel.ERROR once callers are migrated, then delete the API.
  • A custom Lint check (a Detector that reports an Issue with Severity.ERROR) can ban an API that you do not own, such as android.util.Log or LiveData in migrated modules.
  • A lint baseline (lint { baseline = file("lint-baseline.xml") }) records the existing violations, so a new rule fails only on new code while the old violations are burned down.
ToolRole
Feature flag (for example Firebase Remote Config)Switch old and new paths at runtime and roll back without a release
@Deprecated with ReplaceWithWarning or error on your own old APIs, with an IDE quick fix
Custom Lint DetectorBan APIs you do not own, scoped to the modules you choose
Lint baselineEnforce a new rule on new code without fixing every old violation first
Codemod (OpenRewrite, scripted refactor, IDE structural replace)Bulk mechanical changes such as renames and import swaps

Measure progress with a number the team can see, such as migrated screens divided by total screens, or the count of remaining usages of the old API from a Lint report. Keep the dual-path period short: while both paths exist, you maintain and test two implementations.

Notes

  • The strangler pattern replaces a system incrementally behind a seam (interface, factory or navigation entry), instead of a big-bang rewrite.
  • A migration flag should be remotely controlled (for example Firebase Remote Config) so you can roll back without shipping a new build. A build-time flag cannot do that.
  • Read the flag once when the screen or feature starts, not on every recomposition or bind, so the UI does not switch mid-session.
  • @Deprecated needs a message. Add ReplaceWith(...) for the IDE quick fix and raise level from WARNING to ERROR (or HIDDEN) as the migration finishes.
  • Custom Lint checks live in a separate JVM module that depends on lint-api and registers an IssueRegistry. Apps consume them with lintChecks(project(":lint-rules")).
  • A lint baseline file lets a new rule fail only on new violations. Regenerate it with ./gradlew updateLintBaseline as old violations are fixed, so it only shrinks.
  • Codemods handle mechanical changes (renames, import swaps). Changes in behaviour, state handling or error handling need human review.
  • Delete the old path and the flag once the new path has run at 100 percent long enough to trust it. Old flags left in place are tech debt of their own.
  • Measure progress with a count the build can produce, such as remaining usages reported by Lint or the number of migrated screens, not by pull requests merged.
  • For XML to Compose, ComposeView hosts Compose inside existing Views and AndroidView hosts Views inside Compose, so screens can move one at a time.

Code example

A screen migration behind a seam: one interface, the legacy XML implementation, the new Compose implementation, and a factory that reads a remote flag once.

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
 
interface FeatureFlags {
    val useComposeProfile: Boolean   // backed by a remote config value
}
 
interface ProfileScreen {
    fun attach(container: ViewGroup)
}
 
class LegacyProfileScreen(private val viewModel: ProfileViewModel) : ProfileScreen {
    override fun attach(container: ViewGroup) {
        val view = LayoutInflater.from(container.context)
            .inflate(R.layout.profile_screen, container, false)
        container.addView(view)
        // existing ViewBinding code observes viewModel here
    }
}
 
class ComposeProfileScreen(private val viewModel: ProfileViewModel) : ProfileScreen {
    override fun attach(container: ViewGroup) {
        container.addView(
            ComposeView(container.context).apply {
                setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
                setContent { ProfileRoute(viewModel) }   // the new @Composable screen
            }
        )
    }
}
 
class ProfileScreenFactory(private val flags: FeatureFlags) {
    fun create(viewModel: ProfileViewModel): ProfileScreen =
        if (flags.useComposeProfile) ComposeProfileScreen(viewModel) else LegacyProfileScreen(viewModel)
}
 
// Old API in a module you own: callers get a warning and a quick fix.
@Deprecated(
    message = "Use ProfileScreenFactory.create()",
    replaceWith = ReplaceWith("ProfileScreenFactory(flags).create(viewModel)"),
    level = DeprecationLevel.WARNING,
)
fun createLegacyProfile(viewModel: ProfileViewModel): ProfileScreen = LegacyProfileScreen(viewModel)
  • ProfileViewModel, ProfileRoute and R.layout.profile_screen are the app's existing ViewModel, new composable and old layout; both implementations share the ViewModel, so the business logic is not rewritten.
  • The calling Fragment or Activity only sees ProfileScreen; the flag is read once, in the factory.
  • DisposeOnViewTreeLifecycleDestroyed ties the composition to the host's lifecycle, which matters when a ComposeView lives inside a Fragment.
  • When the flag has been at 100 percent long enough, delete LegacyProfileScreen, the layout, the flag and the deprecated function together.

Run the idea in plain Kotlin

interface PaymentProcessor {
  fun charge(amountCents: Int): String
}

class LegacyPaymentProcessor : PaymentProcessor {
  override fun charge(amountCents: Int): String = "Legacy: charged " + amountCents + " cents"
}

class NewPaymentProcessor : PaymentProcessor {
  override fun charge(amountCents: Int): String = "New: charged " + amountCents + " cents (idempotent)"
}

class RemoteFlags(private val values: Map<String, Boolean>) {
  fun isEnabled(key: String): Boolean = values[key] ?: false
}

class PaymentProcessorFactory(private val flags: RemoteFlags) {
  fun create(): PaymentProcessor =
      if (flags.isEnabled("new_payments")) NewPaymentProcessor() else LegacyPaymentProcessor()
}

fun main() {
  val off = PaymentProcessorFactory(RemoteFlags(mapOf("new_payments" to false))).create()
  val on = PaymentProcessorFactory(RemoteFlags(mapOf("new_payments" to true))).create()
  println("Flag OFF: " + off.charge(500))
  println("Flag ON:  " + on.charge(500))

  // Progress: migrated screens / total screens
  val migrated = 42
  val total = 120
  println("Migrated " + migrated + " of " + total + " screens (" + (migrated * 100 / total) + "%)")
}

Expected output:

Flag OFF: Legacy: charged 500 cents
Flag ON:  New: charged 500 cents (idempotent)
Migrated 42 of 120 screens (35%)

In production

Deep link crash after a navigation migration
  • A team moved several screens from Fragment navigation to Navigation Compose and, in the same release, deleted the old Fragment classes.
  • Old deep links still pointed at the old navigation graph, and opening one on a cold start crashed because the Fragment class no longer existed.
  • Because the old path was gone, rolling back meant shipping a hotfix release.
The fix
  • Kept the old graph and Fragments behind a remote flag until the new graph had handled every deep link in production.
  • Added instrumented tests that launch the app from each declared deep link.
  • Deleted the old Fragments and the flag in a later release, after the flag had been at 100 percent without new crashes.
A codemod introduced a NewApi crash
  • A codemod replaced ContextCompat.getColor(context, id) with context.getColor(id) across the app to "drop a compat call".
  • Context.getColor(int) was added in API 23, and the app's minSdk was 21. Devices on API 21 and 22 crashed with NoSuchMethodError.
  • Lint's NewApi check would have caught it, but the new errors were absorbed into the lint baseline when someone regenerated it to make CI green, and CI tests only ran on newer emulators.
The fix
  • Reverted to ContextCompat.getColor, which handles older API levels.
  • Added a CI check that fails when the lint baseline file gains entries, so it can only shrink.
  • Added a CI test run on an emulator at the app's minSdk.

Common mistakes

  • Big-bang rewrite. One bug blocks the whole release and nothing ships for months. Migrate incrementally behind a seam.
  • Deleting the old path too early. Without the old code, rollback needs a new release. Keep it until the new path has run at 100 percent long enough to trust.
  • Leaving both paths forever. Every extra week of dual paths means double maintenance and testing. Remove the old path and the flag once the migration is done.
  • No check against the old API. New features copy old patterns. Add @Deprecated for your own APIs and a custom Lint check for APIs you do not own.
  • Regenerating the lint baseline to make CI green. That silently accepts new violations. The baseline should only shrink.
  • Measuring progress by pull requests. A pull request can touch one screen or thirty. Count migrated screens or remaining usages instead.

Interview questions

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

“How would you migrate 200 XML screens to Jetpack Compose without stopping feature work?”

“How do you stop code from going back to a deprecated API?”

“What is the strangler pattern, and when would you not use it?”

“How do you decide which tech debt to pay down first?”

Quiz

What is the main purpose of a remote feature flag in a strangler-pattern migration?

Which declaration compiles and makes calls to oldApi() a compiler error with an IDE quick fix?

What does a lint baseline file do?

When should you delete the old implementation after a flagged migration?

0 of 4 answered

Mini task

15-minute exercise: ban an API with a custom Lint check

  1. Pick an API to ban in new code, for example direct android.util.Log calls when your team has its own logging wrapper.
  2. Create a JVM module :lint-rules (kotlin("jvm") plugin) with compileOnly("com.android.tools.lint:lint-api:<version>"), using the Lint version that matches your AGP as described in the Android Lint API guide.
  3. Write NoAndroidLogDetector, a Detector that implements SourceCodeScanner. Return the method names in getApplicableMethodNames(), and in visitMethodCall check that the method belongs to android.util.Log before calling context.report(...).
  4. Define the Issue with Issue.create(...), Category.CORRECTNESS, Severity.ERROR and an Implementation using Scope.JAVA_FILE_SCOPE, and register it in an IssueRegistry subclass listed in META-INF/services/com.android.tools.lint.client.api.IssueRegistry.
  5. In the app module, add lintChecks(project(":lint-rules")) and run ./gradlew :app:lintDebug.
  6. If there are existing calls, add lint { baseline = file("lint-baseline.xml") }, run ./gradlew :app:updateLintBaseline to create the baseline, then add a new Log.d call and confirm lint fails on it.

Done condition: ./gradlew :app:lintDebug fails on a new android.util.Log call, the existing calls are recorded in the baseline, and removing the new call makes lint pass.

Next: Logging, metrics and tracing on mobile