Architecture at scale cheat sheet

Revise Android architecture at scale: clean layers, use cases, Gradle modularization, type-safe Navigation Compose, and Firebase Remote Config feature flags.

Key ideas

  1. Google's architecture guide marks the domain layer as optional; UI and data layers are recommended for every Android app.
  2. Add a use case only when several ViewModels share a rule or one operation coordinates several repositories; a one-line pass-through is noise.
  3. Prefer implementation over api in Gradle so a module does not expose its own dependencies to its consumers.
  4. Feature modules must not depend on each other; shared types go in a core module and cross-feature navigation is wired in :app.
  5. Type-safe Navigation Compose (2.8+) uses @Serializable route objects; pass IDs, not large objects, as route arguments.
  6. Set in-app defaults with setDefaultsAsync() for every Remote Config key; without a default getBoolean() returns false.
  7. runCatching inside a suspend function also catches CancellationException; rethrow it or catch only the exceptions you expect.
  8. Hide Firebase behind a FeatureFlags interface in a core module so feature modules and tests stay decoupled.
  9. A domain model is a plain Kotlin data class; @Entity or @SerializedName on it means a data-layer detail has leaked.
  10. Too many Gradle modules or layers slow builds and onboarding; match structure to the size of the app and the team.

APIs at a glance

API or termUse it for
UserRepositoryInterface the ViewModel depends on; implement with network, Room, or a fake for tests.
operator fun invokeMakes a use case callable as getUser(id) instead of getUserUseCase.execute(id).
implementation vs apiGradle dependency scope; implementation hides transitive deps from consumers, api exposes them.
@SerializableMarks route classes for type-safe Navigation Compose 2.8+; apply the Kotlin serialization plugin per module.
NavController.navigateToX()Extension a feature exposes so other modules can navigate without importing the feature.
NavGraphBuilder.xScreen()Extension a feature contributes to the app's single NavHost; keep screen composables internal.
setDefaultsAsync()Sets in-app defaults for Remote Config keys before any fetch; covers first launch and offline.
fetchAndActivate()Fetches and activates Remote Config values; returns Task<Boolean>; call .await() with coroutines.
FeatureFlags interfaceHides Firebase behind a core-module contract so feature modules and tests use a fake.
@BindsHilt annotation binding an interface to its implementation in a @Module @InstallIn(SingletonComponent::class).
toRoute<T>()Reads a typed route from a backStackEntry or savedStateHandle in Navigation Compose 2.8+.
catch operatorHandles upstream exceptions in a Flow; a try inside map only covers that lambda.

Snippets

Use case that rethrows CancellationException

data class User(val id: String, val displayName: String)
 
interface UserRepository {
    suspend fun getUserById(id: String): User?
}
 
class UserNotFoundException(id: String) : Exception("No user $id")
class MissingDisplayNameException(id: String) : Exception("User $id has no display name")
 
class GetUserUseCase @Inject constructor(private val repository: UserRepository) {
    suspend operator fun invoke(id: String): Result<User> =
        try {
            val user = repository.getUserById(id) ?: throw UserNotFoundException(id)
            if (user.displayName.isBlank()) throw MissingDisplayNameException(id)
            Result.success(user)
        } catch (e: CancellationException) {
            throw e
        } catch (e: Exception) {
            Result.failure(e)
        }
}

Type-safe route and navigation extension

@Serializable
data class ProfileRoute(val userId: String)
 
@Composable
internal fun ProfileScreen(userId: String, onBack: () -> Unit, onOpenSettings: () -> Unit) {
    // Profile UI for userId
}
 
fun NavController.navigateToProfile(userId: String) {
    navigate(ProfileRoute(userId))
}
 
fun NavGraphBuilder.profileScreen(onBack: () -> Unit, onOpenSettings: () -> Unit) {
    composable<ProfileRoute> { entry ->
        val route = entry.toRoute<ProfileRoute>()
        ProfileScreen(userId = route.userId, onBack = onBack, onOpenSettings = onOpenSettings)
    }
}

FeatureFlags interface with kill-switch

interface FeatureFlags {
    fun isCheckoutV2Enabled(): Boolean
}
 
class FirebaseFeatureFlags(
    private val remoteConfig: FirebaseRemoteConfig,
) : FeatureFlags {
    override fun isCheckoutV2Enabled(): Boolean {
        if (remoteConfig.getBoolean(CHECKOUT_V2_KILL_SWITCH)) return false
        return remoteConfig.getBoolean(CHECKOUT_V2)
    }
 
    private companion object {
        const val CHECKOUT_V2 = "checkout_v2_enabled"
        const val CHECKOUT_V2_KILL_SWITCH = "checkout_v2_kill_switch"
    }
}

Rules of thumb

  • Prefer implementation over api unless a public signature exposes the dependency's types to consumers.
  • Never put a NavController inside a ViewModel; expose UI state and let the screen call a navigation lambda.
  • Never use runCatching around a suspend call without rethrowing CancellationException.
  • Prefer a direct repository call from the ViewModel over a one-line pass-through use case.
  • Never delete a Remote Config console parameter before removing the code path that reads it.
  • Prefer internal visibility for classes in feature and implementation modules to turn boundaries into compile errors.

Gotchas

  • Pass-through use case. A use case that only forwards to one repository method adds a file and a hop with no logic. Call the repository from the ViewModel until a shared rule is worth extracting.
  • runCatching swallowing cancellation. It catches CancellationException, so a cancelled coroutine keeps running and returns a failure instead of stopping. Rethrow CancellationException or catch only expected exceptions like IOException.
  • Large objects in route arguments. Route arguments live in the back stack's saved state, so big objects bloat it and can trigger TransactionTooLargeException. Pass an ID and load the data in the destination's ViewModel.
  • No in-app defaults for Remote Config. getBoolean() returns false for any key that was never activated, silently turning a feature off on first launch or after a fetch failure. Add a default in the same change that adds the flag.
  • Feature-to-feature dependency. If :feature:profile imports a type from :feature:settings, the two features are coupled and a cycle is one import away. Move shared types to a core module and wire navigation in :app.
  • try inside map for Flow errors. A try or runCatching inside map does not see exceptions thrown by the upstream Flow. Use the catch operator for upstream errors; after catch emits, the flow completes.

Quick interview answers

When should you add a domain layer and use cases in an Android app?

Google's architecture guide marks the domain layer as optional; add it when business rules are reused across several ViewModels or when one operation coordinates several repositories. A one-line pass-through use case that only forwards to a single repository call is noise and should be skipped.

What is the difference between api and implementation in Gradle, and when do you use each?

implementation keeps a dependency private to the module, so consumers do not recompile when it changes; api exposes the dependency's types to every consumer. Use api only when a module's public function signature returns or accepts a type from that dependency; default to implementation.

How do you handle cross-feature navigation in a modularized Android app?

Feature modules must not depend on each other; each feature exposes a NavController.navigateToX() extension and a NavGraphBuilder.xScreen() extension, and the app module wires the callbacks. Pass IDs as @Serializable route arguments and load the full data in the destination's ViewModel to keep saved state small.

Why must you set in-app defaults for Firebase Remote Config, and what happens without them?

getBoolean() returns false for any key that has never been activated, which silently turns a feature off on first launch, offline launch, or after a fetch failure. Call setDefaultsAsync() with a map of every key the app reads, in the same change that introduces the flag.

What is wrong with using runCatching inside a suspend function, and how do you fix it?

runCatching catches CancellationException as well, so a cancelled coroutine keeps executing and returns a failure result instead of stopping. Rethrow CancellationException explicitly, or catch only the specific exceptions you expect such as IOException and HttpException.

How do you keep a domain model free of framework annotations?

A domain model is a plain Kotlin data class; if it carries @Entity, @SerializedName, or @ColumnInfo, a database or JSON detail has leaked into it. Keep the mapping in the data layer and, if the domain module is a plain kotlin("jvm") module, Android and Room classes cannot even be imported, which enforces the boundary for free.

Go deeper