Managing tech debt and migrations
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. RaiseleveltoDeprecationLevel.ERRORonce callers are migrated, then delete the API.- A custom Lint check (a
Detectorthat reports anIssuewithSeverity.ERROR) can ban an API that you do not own, such asandroid.util.LogorLiveDatain 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.
| Tool | Role |
|---|---|
| Feature flag (for example Firebase Remote Config) | Switch old and new paths at runtime and roll back without a release |
@Deprecated with ReplaceWith | Warning or error on your own old APIs, with an IDE quick fix |
Custom Lint Detector | Ban APIs you do not own, scoped to the modules you choose |
| Lint baseline | Enforce 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.
@Deprecatedneeds amessage. AddReplaceWith(...)for the IDE quick fix and raiselevelfromWARNINGtoERROR(orHIDDEN) as the migration finishes.- Custom Lint checks live in a separate JVM module that depends on
lint-apiand registers anIssueRegistry. Apps consume them withlintChecks(project(":lint-rules")). - A lint baseline file lets a new rule fail only on new violations. Regenerate it with
./gradlew updateLintBaselineas 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,
ComposeViewhosts Compose inside existing Views andAndroidViewhosts 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,ProfileRouteandR.layout.profile_screenare the app's existing ViewModel, new composable and old layout; both implementations share the ViewModel, so the business logic is not rewritten.- The calling
FragmentorActivityonly seesProfileScreen; the flag is read once, in the factory. DisposeOnViewTreeLifecycleDestroyedties the composition to the host's lifecycle, which matters when aComposeViewlives inside aFragment.- 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
- 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.
- 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 replaced
ContextCompat.getColor(context, id)withcontext.getColor(id)across the app to "drop a compat call". Context.getColor(int)was added in API 23, and the app'sminSdkwas 21. Devices on API 21 and 22 crashed withNoSuchMethodError.- Lint's
NewApicheck 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.
- 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
@Deprecatedfor 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
- Pick an API to ban in new code, for example direct
android.util.Logcalls when your team has its own logging wrapper. - Create a JVM module
:lint-rules(kotlin("jvm")plugin) withcompileOnly("com.android.tools.lint:lint-api:<version>"), using the Lint version that matches your AGP as described in the Android Lint API guide. - Write
NoAndroidLogDetector, aDetectorthat implementsSourceCodeScanner. Return the method names ingetApplicableMethodNames(), and invisitMethodCallcheck that the method belongs toandroid.util.Logbefore callingcontext.report(...). - Define the
IssuewithIssue.create(...),Category.CORRECTNESS,Severity.ERRORand anImplementationusingScope.JAVA_FILE_SCOPE, and register it in anIssueRegistrysubclass listed inMETA-INF/services/com.android.tools.lint.client.api.IssueRegistry. - In the app module, add
lintChecks(project(":lint-rules"))and run./gradlew :app:lintDebug. - If there are existing calls, add
lint { baseline = file("lint-baseline.xml") }, run./gradlew :app:updateLintBaselineto create the baseline, then add a newLog.dcall 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.