Architecture at scale cheat sheet
Key ideas
- Google's architecture guide marks the domain layer as optional; UI and data layers are recommended for every Android app.
- Add a use case only when several ViewModels share a rule or one operation coordinates several repositories; a one-line pass-through is noise.
- Prefer
implementationoverapiin Gradle so a module does not expose its own dependencies to its consumers. - Feature modules must not depend on each other; shared types go in a core module and cross-feature navigation is wired in
:app. - Type-safe Navigation Compose (2.8+) uses
@Serializableroute objects; pass IDs, not large objects, as route arguments. - Set in-app defaults with
setDefaultsAsync()for every Remote Config key; without a defaultgetBoolean()returnsfalse. runCatchinginside a suspend function also catchesCancellationException; rethrow it or catch only the exceptions you expect.- Hide Firebase behind a
FeatureFlagsinterface in a core module so feature modules and tests stay decoupled. - A domain model is a plain Kotlin
data class;@Entityor@SerializedNameon it means a data-layer detail has leaked. - 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 term | Use it for |
|---|---|
UserRepository | Interface the ViewModel depends on; implement with network, Room, or a fake for tests. |
operator fun invoke | Makes a use case callable as getUser(id) instead of getUserUseCase.execute(id). |
implementation vs api | Gradle dependency scope; implementation hides transitive deps from consumers, api exposes them. |
@Serializable | Marks 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 interface | Hides Firebase behind a core-module contract so feature modules and tests use a fake. |
@Binds | Hilt 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 operator | Handles 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
implementationoverapiunless a public signature exposes the dependency's types to consumers. - Never put a
NavControllerinside a ViewModel; expose UI state and let the screen call a navigation lambda. - Never use
runCatchingaround a suspend call without rethrowingCancellationException. - 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
internalvisibility 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. RethrowCancellationExceptionor catch only expected exceptions likeIOException. - 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()returnsfalsefor 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:profileimports 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
tryorrunCatchinginsidemapdoes not see exceptions thrown by the upstream Flow. Use thecatchoperator for upstream errors; aftercatchemits, 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.