When an Android application starts growing, putting API calls, business
rules, database operations, and UI code into one Activity or Composable
quickly becomes difficult to maintain.
A small feature may work perfectly today, but what happens when:
- The API response format changes?
- You need to add offline support?
- The same business logic is required on another screen?
- You want to unit-test business rules without launching Android?
- Several developers need to work on different parts of the application?
This is where software architecture, design patterns, and SOLID
principles become important.
In this guide, we will understand the concepts step by step, compare
MVC, MVP, and MVVM, explore Clean Architecture, learn commonly used
design patterns, apply SOLID principles, and finish with Android-focused
interview questions.
Important: These concepts solve different problems. MVC, MVP, and
MVVM describe ways to organize presentation logic. Clean Architecture
describes dependency boundaries and separation of concerns. Design
patterns are reusable solutions to recurring design problems. SOLID is
a set of principles that helps us design maintainable object-oriented
code.
1. What is software architecture?
Software architecture is the high-level structure of an application. It
defines how major parts of the system are organized, how they
communicate, and which responsibilities belong to each part.
Think about a food delivery application:
- The UI displays restaurants and orders.
- The presentation layer manages screen state and user actions.
- The domain layer contains business rules such as placing an order.
- The data layer communicates with APIs, databases, and other sources.
A good architecture aims for:
- Separation of concerns: Each component has a clear responsibility.
- Maintainability: Changes in one area should not unnecessarily affect other areas.
- Testability: Business logic should be testable independently.
- Reusability: Shared logic should not be duplicated.
- Scalability: New features should fit into the existing structure.
- Understandability: Developers should be able to locate and understand code quickly.
Architecture is not about creating the maximum number of packages or
classes. It is about choosing boundaries that make the application
easier to change.
2. MVC --- Model View Controller
MVC stands for Model--View--Controller. It separates an application
into three main responsibilities.
- Model: Holds application data and business rules.
- View: Displays information to the user.
- Controller: Handles user input and coordinates updates between the Model and View.
MVC flow
User Action
|
v
View
|
v
Controller
|
v
Model
|
v
Controller updates View
Simple example
Imagine a login screen.
- The View contains the email and password fields and the login button.
- The Controller handles the button click and coordinates login.
- The Model represents the user data and authentication operation.
A simplified Kotlin example:
data class User(
val email: String
)
class LoginModel {
fun login(email: String, password: String): User? {
if (email.isBlank() || password.isBlank()) return null
// Simplified example. A real app calls a repository/API.
return User(email = email)
}
}
class LoginController(
private val model: LoginModel,
private val view: LoginView
) {
fun onLoginClicked(email: String, password: String) {
val user = model.login(email, password)
if (user != null) {
view.showSuccess("Welcome ${user.email}")
} else {
view.showError("Please enter valid details")
}
}
}
interface LoginView {
fun showSuccess(message: String)
fun showError(message: String)
}
This is a conceptual example, not a complete Android implementation. In
Android, the View might be an Activity, Fragment, or custom UI
component.
Advantages of MVC
- Easy to understand for small applications.
- Separates UI rendering from coordination logic.
- Can be useful in frameworks that naturally provide controller structures.
Disadvantages of MVC
- Controllers can become large.
- UI and business logic may become tightly coupled if boundaries are not enforced.
- Testing can be difficult when the controller depends directly on Android UI classes.
When should you use it? MVC can work well for small applications or
platforms where the framework strongly encourages the pattern. For
larger Android applications, teams often prefer MVVM with additional
architectural boundaries.
3. MVP --- Model View Presenter
MVP stands for Model--View--Presenter. It is similar to MVC, but the
Presenter takes responsibility for presentation logic and communicates
with the View through an interface.
The main components are:
- Model: Provides data and business operations.
- View: Displays data and forwards user actions.
- Presenter: Receives actions, obtains data, and tells the View what to display.
MVP flow
User Action
|
v
View
|
v
Presenter
|
v
Model
|
v
Presenter
|
v
View
Kotlin example
interface LoginContract {
interface View {
fun showLoading()
fun hideLoading()
fun showMessage(message: String)
}
interface Presenter {
fun login(email: String, password: String)
}
}
class LoginPresenter(
private val view: LoginContract.View,
private val authenticate: (String, String) -> Boolean
) : LoginContract.Presenter {
override fun login(email: String, password: String) {
if (email.isBlank() || password.isBlank()) {
view.showMessage("Email and password are required")
return
}
view.showLoading()
val success = authenticate(email, password)
view.hideLoading()
view.showMessage(
if (success) "Login successful" else "Login failed"
)
}
}
The Activity or Fragment implements LoginContract.View and connects
the UI to the Presenter.
Advantages of MVP
- Presentation logic is moved out of the Activity or Fragment.
- View interfaces make Presenter tests easier.
- The View can be replaced without rewriting the Presenter, provided the contract remains stable.
Disadvantages of MVP
- The Presenter can become large if it handles too many responsibilities.
- The View interface may contain many methods.
- Developers must manage the View lifecycle carefully. A Presenter that retains an Activity can cause memory leaks.
- More interfaces and wiring can mean additional boilerplate.
When should you use it? MVP is useful in legacy Android applications
or projects where explicit View interfaces and presenter-driven tests
are preferred.
4. MVVM --- Model View ViewModel
MVVM stands for Model--View--ViewModel. It is widely used in modern
Android development, particularly with Android Jetpack and Jetpack
Compose.
The components are:
- Model: Data sources and business operations, commonly accessed through repositories and use cases.
- View: Activity, Fragment, or Compose UI. It observes state and renders the screen.
- ViewModel: Holds and exposes UI state, handles UI actions, and coordinates operations needed by the screen.
MVVM flow
User Action
|
v
View
|
v
ViewModel
|
v
Repository / Use Case
|
v
API / Database
|
v
Repository / Use Case
|
v
ViewModel updates UI State
|
v
View observes state
The ViewModel should not hold a reference to an Activity, Fragment,
View, or other lifecycle-bound UI object.
Android Kotlin example
First, define a UI state:
data class LoginUiState(
val isLoading: Boolean = false,
val message: String? = null
)
Create a repository contract:
interface AuthRepository {
suspend fun login(email: String, password: String): Result<Unit>
}
Then implement the ViewModel:
class LoginViewModel(
private val authRepository: AuthRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(LoginUiState())
val uiState: StateFlow<LoginUiState> = _uiState.asStateFlow()
fun login(email: String, password: String) {
if (email.isBlank() || password.isBlank()) {
_uiState.update {
it.copy(message = "Email and password are required")
}
return
}
viewModelScope.launch {
_uiState.update {
it.copy(isLoading = true, message = null)
}
val result = authRepository.login(email, password)
_uiState.update {
it.copy(
isLoading = false,
message = result.fold(
onSuccess = { "Login successful" },
onFailure = { error ->
error.message ?: "Login failed"
}
)
)
}
}
}
}
A simplified Jetpack Compose screen:
@Composable
fun LoginScreen(
viewModel: LoginViewModel
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
Column {
if (state.isLoading) {
CircularProgressIndicator()
}
state.message?.let { message ->
Text(text = message)
}
Button(
onClick = {
viewModel.login(
email = "user@example.com",
password = "password"
)
}
) {
Text("Login")
}
}
}
This example demonstrates the direction of communication. A production
screen should collect actual form input, handle one-time effects such as
navigation appropriately, and use dependency injection to provide the
repository.
Advantages of MVVM
- UI state is separated from UI rendering.
- ViewModels survive configuration changes when scoped appropriately.
- StateFlow and Compose work naturally with observable state.
- ViewModels can be tested without creating an Activity.
- Repository abstractions make data sources easier to replace.
Disadvantages of MVVM
- A ViewModel can become a large class if it owns unrelated screen responsibilities.
- Poorly designed state and event handling can create complex UI behavior.
- It does not automatically enforce separation between business logic and data access.
- Teams still need to manage lifecycle, coroutine cancellation, and dependency boundaries correctly.
When should you use it? MVVM is a strong default for modern Android
UI development, especially with Jetpack Compose, StateFlow, and
lifecycle-aware state collection.
5. MVC vs MVP vs MVVM
Area MVC MVP MVVM
Main coordinator Controller Presenter ViewModel
UI communication Controller Presenter calls View observes
coordinates View View interface ViewModel state
View dependency Can be tightly Usually Should be
coupled interface-based lightweight
Testability Depends on Good with View Good with state
separation contracts and injected
dependencies
Common Android Simple or legacy Legacy and Modern Android
use structures explicit apps
contracts
Typical risk Large Controller Large Presenter Large ViewModel
or retained View
Interview point: MVVM is not automatically better in every
situation. Choose a pattern based on the platform, team, application
complexity, testability needs, and existing codebase.
6. Clean Architecture
Clean Architecture focuses on separating business rules from frameworks,
UI, and external data sources.
It is commonly represented as layers:
- Presentation layer: Activities, Fragments, Compose screens, ViewModels, and UI state.
- Domain layer: Business rules, entities, repository contracts, and use cases.
- Data layer: Repository implementations, API services, database, DTOs, and data mapping.
Dependency rule
The most important rule is:
Source-code dependencies should point inward, toward the domain and
business rules.
The domain layer should not depend on Android UI classes, Retrofit,
Room, or other implementation details.
Architecture diagram
+--------------------------------------+
| Presentation |
| Compose / Activity / ViewModel |
+-------------------+------------------+
|
v
+--------------------------------------+
| Domain |
| Use Cases / Entities / |
| Repository Interfaces |
+-------------------+------------------+
^
|
+--------------------------------------+
| Data |
| Repository Implementations / API / |
| Database / DTOs / Mappers |
+--------------------------------------+
The arrows in a real implementation represent dependency direction: the
data implementation depends on domain contracts, while the presentation
layer invokes domain operations. The domain layer remains independent.
Recommended Android project structure
com.example.app
|
+-- presentation
| +-- login
| +-- LoginScreen.kt
| +-- LoginViewModel.kt
| +-- LoginUiState.kt
|
+-- domain
| +-- model
| | +-- User.kt
| +-- repository
| | +-- AuthRepository.kt
| +-- usecase
| +-- LoginUseCase.kt
|
+-- data
+-- repository
| +-- AuthRepositoryImpl.kt
+-- remote
| +-- AuthApi.kt
+-- local
+-- mapper
For a small app, these can be packages in one module. For a larger app,
they may become separate Gradle modules. Do not create modules just to
follow a diagram; introduce boundaries when they provide real value.
Step-by-step Kotlin example
Step 1: Domain model
data class User(
val id: String,
val email: String
)
Step 2: Repository interface
interface AuthRepository {
suspend fun login(
email: String,
password: String
): Result<User>
}
Step 3: Use case
class LoginUseCase(
private val repository: AuthRepository
) {
suspend operator fun invoke(
email: String,
password: String
): Result<User> {
if (email.isBlank()) {
return Result.failure(
IllegalArgumentException("Email is required")
)
}
if (password.isBlank()) {
return Result.failure(
IllegalArgumentException("Password is required")
)
}
return repository.login(email, password)
}
}
Step 4: Data implementation
class AuthRepositoryImpl(
private val api: AuthApi
) : AuthRepository {
override suspend fun login(
email: String,
password: String
): Result<User> = runCatching {
val response = api.login(email, password)
User(
id = response.id,
email = response.email
)
}
}
AuthApi and LoginResponse are simplified placeholders for your
Retrofit or Ktor API definitions.
Step 5: ViewModel
class LoginViewModel(
private val loginUseCase: LoginUseCase
) : ViewModel() {
fun login(email: String, password: String) {
viewModelScope.launch {
val result = loginUseCase(email, password)
result.onSuccess { user ->
// Update success state or emit a UI effect.
}.onFailure { error ->
// Update error state.
}
}
}
}
Why use cases?
A use case represents one application action or business operation, such
as:
- LoginUser
- GetUserProfile
- PlaceOrder
- SyncOfflineTasks
- UploadDocument
Use cases are valuable when they encapsulate meaningful business rules,
coordinate multiple dependencies, or are reused. A use case that only
forwards one method call without adding a useful boundary may be
unnecessary.
Advantages of Clean Architecture
- Business logic is independent of frameworks.
- Repository contracts make testing easier.
- Data sources can be changed with less impact on business rules.
- Responsibilities are clearer as the application grows.
- It supports modularization and parallel development.
Disadvantages
- More interfaces and files can increase initial development time.
- Too many trivial use cases can create unnecessary boilerplate.
- Incorrect dependency direction can make the architecture complicated rather than clean.
- It requires consistency and discipline across the team.
7. MVVM and Clean Architecture: Are they the same?
No. They solve different problems and can be used together.
- MVVM organizes the presentation layer.
- Clean Architecture organizes the application's boundaries and dependency direction.
A typical Android application can use both:
Compose UI
|
v
ViewModel <- MVVM
|
v
Use Case <- Clean Architecture
|
v
Repository Interface <- Domain boundary
|
v
Repository Implementation <- Data layer
|
v
Retrofit / Room / Ktor
This combination is common, but not mandatory for every application.
8. Design Patterns in Android Development
A design pattern is a reusable approach to a recurring software design
problem. Patterns are not ready-made code that must be applied
everywhere. Use them when they simplify a real problem.
8.1 Singleton Pattern
Ensures that a class has one shared instance within a defined scope.
object AppConfig {
const val BASE_URL = "https://api.example.com"
}
Android use cases: Shared configuration or a carefully scoped
manager.
Caution: Avoid turning every dependency into a global singleton.
Global state makes tests and lifecycle management harder. Dependency
injection scopes are often a better choice.
8.2 Factory Pattern
Creates objects while hiding the construction details from the caller.
interface PaymentMethod {
fun pay(amount: Double)
}
class CardPayment : PaymentMethod {
override fun pay(amount: Double) {
println("Paid by card: $amount")
}
}
class UpiPayment : PaymentMethod {
override fun pay(amount: Double) {
println("Paid by UPI: $amount")
}
}
object PaymentFactory {
fun create(type: String): PaymentMethod {
return when (type.lowercase()) {
"card" -> CardPayment()
"upi" -> UpiPayment()
else -> error("Unsupported payment type")
}
}
}
Android use cases: Creating parsers, payment handlers, or
implementations based on configuration.
8.3 Observer Pattern
Allows an object to notify multiple observers when its state changes.
class TemperatureSensor {
private val observers = mutableListOf<(Float) -> Unit>()
fun observe(observer: (Float) -> Unit) {
observers += observer
}
fun updateTemperature(value: Float) {
observers.forEach { it(value) }
}
}
Android use cases: LiveData, Flow, StateFlow, and reactive UI
updates use observer-like ideas.
8.4 Repository Pattern
Provides a consistent interface for accessing data, hiding whether it
comes from a remote API, local database, cache, or another source.
interface UserRepository {
suspend fun getUser(id: String): User
}
class UserRepositoryImpl(
private val api: UserApi,
private val dao: UserDao
) : UserRepository {
override suspend fun getUser(id: String): User {
return dao.getUser(id)?.toDomain()
?: api.getUser(id).toDomain()
}
}
Android use cases: Combining Room, Retrofit/Ktor, caching, and
offline-first behavior.
8.5 Strategy Pattern
Defines a family of interchangeable algorithms behind a common
interface.
interface SortStrategy {
fun sort(items: List<Int>): List<Int>
}
class AscendingSort : SortStrategy {
override fun sort(items: List<Int>) = items.sorted()
}
class DescendingSort : SortStrategy {
override fun sort(items: List<Int>) = items.sortedDescending()
}
class NumberSorter(
private val strategy: SortStrategy
) {
fun sort(items: List<Int>) = strategy.sort(items)
}
Android use cases: Different sorting, pricing, validation, or
authentication strategies.
8.6 Builder Pattern
Constructs complex objects step by step.
data class NotificationConfig(
val title: String,
val message: String,
val priority: Int,
val soundEnabled: Boolean
)
class NotificationConfigBuilder {
var title: String = ""
var message: String = ""
var priority: Int = 0
var soundEnabled: Boolean = true
fun build() = NotificationConfig(
title = title,
message = message,
priority = priority,
soundEnabled = soundEnabled
)
}
Usage:
val config = NotificationConfigBuilder().apply {
title = "New task"
message = "A task has been assigned"
priority = 2
}.build()
Android use cases: Configuring complex objects, test data, or
notification options. Kotlin named and default arguments may make a
Builder unnecessary for simpler objects.
8.7 Dependency Injection Pattern
Supplies an object with its dependencies instead of making it construct
those dependencies itself.
class ProfileViewModel(
private val repository: UserRepository
) : ViewModel()
A dependency injection framework such as Koin or Hilt can create
and provide the repository and ViewModel.
Benefits: Lower coupling, easier testing, and centralized dependency
creation.
9. SOLID Principles
SOLID is a group of five object-oriented design principles. They help
developers create code that is easier to extend, test, and maintain.
S --- Single Responsibility Principle
A class should have one clear responsibility, or one primary reason to
change.
Bad example:
class UserManager {
fun login() { /* authentication */ }
fun saveUser() { /* database operation */ }
fun sendEmail() { /* notification */ }
}
This class handles authentication, persistence, and notifications.
Better approach:
class AuthService {
fun login() { /* authentication */ }
}
class UserLocalDataSource {
fun saveUser() { /* database operation */ }
}
class EmailService {
fun sendEmail() { /* notification */ }
}
Android example: Keep API operations in data sources or services,
business rules in domain operations, and UI state management in
ViewModels.
O --- Open/Closed Principle
Software entities should be open for extension but closed for
modification.
You should be able to add a new behavior without repeatedly editing
stable existing logic.
Example:
interface DiscountStrategy {
fun calculate(total: Double): Double
}
class RegularDiscount : DiscountStrategy {
override fun calculate(total: Double) = total * 0.05
}
class PremiumDiscount : DiscountStrategy {
override fun calculate(total: Double) = total * 0.15
}
class Checkout(
private val discountStrategy: DiscountStrategy
) {
fun finalPrice(total: Double): Double {
return total - discountStrategy.calculate(total)
}
}
To add another discount type, create another implementation rather than
adding more conditions inside Checkout.
L --- Liskov Substitution Principle
Objects of a subtype should be usable wherever the parent type is
expected without breaking the correctness of the program.
Problematic example:
open class Bird {
open fun fly() {}
}
class Penguin : Bird() {
override fun fly() {
error("Penguins cannot fly")
}
}
A caller expecting every Bird to fly may fail when it receives a
Penguin.
Better approach: Model capabilities explicitly.
interface Bird
interface FlyingBird : Bird {
fun fly()
}
class Eagle : FlyingBird {
override fun fly() {
println("Eagle is flying")
}
}
class Penguin : Bird
Do not force a subtype to support behavior that does not make sense for
it.
I --- Interface Segregation Principle
Clients should not be forced to depend on methods they do not use.
Prefer small, focused interfaces over large interfaces with unrelated
responsibilities.
Problematic interface:
interface Device {
fun print()
fun scan()
fun fax()
}
A basic printer may not support scanning or faxing.
Better approach:
interface Printer {
fun print()
}
interface Scanner {
fun scan()
}
interface FaxMachine {
fun fax()
}
class BasicPrinter : Printer {
override fun print() {
println("Printing")
}
}
D --- Dependency Inversion Principle
High-level business logic should not depend directly on low-level
implementation details. Both should depend on abstractions.
Problematic example:
class UserViewModel {
private val repository = FirebaseUserRepository()
}
The ViewModel is tightly coupled to a concrete Firebase implementation.
Better approach:
interface UserRepository {
suspend fun getUser(): User
}
class UserViewModel(
private val repository: UserRepository
) : ViewModel()
Now the ViewModel depends on an abstraction. Production can use a
Firebase-backed implementation, while tests can use a fake repository.
SOLID quick revision
Principle Main idea Quick question
SRP One responsibility Does this class have
unrelated reasons to
change?
OCP Extend without Can I add a behavior
modifying stable code without changing
existing logic?
LSP Subtypes remain Can this implementation
substitutable safely replace its
parent type?
ISP Small focused Does a client depend on
interfaces methods it never uses?
DIP Depend on abstractions Does high-level logic
know concrete
infrastructure details?
10. How these concepts work together in a real Android app
Consider an offline-first task management application.
A user opens the task list, creates a task, and expects it to be saved
even if the network is unavailable.
A possible architecture is:
TaskListScreen (Compose)
|
v
TaskViewModel
|
v
GetTasksUseCase / CreateTaskUseCase
|
v
TaskRepository (domain interface)
|
v
TaskRepositoryImpl
/ \
v v
Room Remote API
How each concept contributes:
- MVVM: The ViewModel exposes task-list UI state to Compose.
- Clean Architecture: Use cases and repository contracts keep business rules independent of Android and networking frameworks.
- Repository Pattern: The repository decides how local and remote data are coordinated.
- Observer Pattern: Flow or StateFlow can notify the UI when task data changes.
- Dependency Injection: Koin or Hilt provides the required implementations.
- SOLID: Small responsibilities and abstractions make the feature easier to extend and test.
A useful rule is to make the local database the source of truth in a
genuinely offline-first design. The UI observes local data, while
synchronization updates the local database as remote operations succeed.
The exact sync strategy depends on conflict resolution, retries, and
product requirements.
11. Common Android architecture mistakes
- Putting everything in the ViewModel: Split responsibilities when a ViewModel starts handling unrelated features or complex business rules.
- Calling APIs directly from the UI: Move data access behind repositories or domain operations.
- Creating interfaces for every class: Abstractions are useful at boundaries, but unnecessary interfaces add indirection.
- Making every operation a use case: Create use cases for meaningful business actions, not merely to increase file count.
- Using global singletons for everything: Prefer controlled dependency injection scopes.
- Ignoring lifecycle: Avoid retaining Activity or View references in ViewModels and presenters.
- Mixing UI models and API DTOs: Map external response models into models appropriate for the domain or presentation layer.
- Treating all UI events as permanent state: Model persistent screen information as state; handle one-time effects such as navigation and transient messages deliberately.
- Overengineering small applications: Start with the simplest structure that preserves clear responsibilities, then introduce more boundaries as complexity grows.
12. Android Architecture Interview Questions and Answers
Beginner-level questions
1. What is software architecture?
Software architecture defines the structure of an application, its major
components, their responsibilities, and how they communicate.
2. What is MVC?
MVC separates an application into Model, View, and Controller. The
Controller coordinates user input and updates involving the Model and
View.
3. What is MVP?
MVP separates Model, View, and Presenter. The Presenter handles
presentation logic and communicates with the View through an interface.
4. What is MVVM?
MVVM separates Model, View, and ViewModel. The View observes UI state
exposed by the ViewModel and forwards user actions to it.
5. What is the main difference between MVP and MVVM?
In a typical MVP design, the Presenter directly calls methods on a View
interface. In MVVM, the View observes state exposed by the ViewModel.
Exact implementations can vary.
6. What is a ViewModel in Android?
An Android ViewModel stores and manages UI-related data in a
lifecycle-conscious way. It is commonly used to expose screen state and
coordinate operations for a UI.
7. Does ViewModel survive screen rotation?
An AndroidX ViewModel generally survives configuration changes when it
remains in the same ViewModelStoreOwner scope. It is not automatically
persistent across process death.
8. What is a Repository?
A Repository provides an abstraction over data sources such as APIs,
databases, and caches.
Intermediate-level questions
9. What is Clean Architecture?
Clean Architecture separates concerns into layers and keeps source-code
dependencies pointing toward business rules. It aims to keep the domain
independent of frameworks and infrastructure.
10. What is the Dependency Rule?
Dependencies in source code should point inward. Outer layers can depend
on inner layers, but inner business rules should not depend on outer
implementation details.
11. What is a Use Case?
A Use Case represents a specific application action or business
operation, such as creating a task or logging in a user.
12. Can MVVM be used with Clean Architecture?
Yes. MVVM structures the presentation layer, while Clean Architecture
defines boundaries across the application.
13. What is Dependency Injection?
Dependency Injection is a technique in which an object receives its
dependencies from outside rather than constructing concrete dependencies
itself.
14. What is the difference between Dependency Injection and Dependency
Inversion?
Dependency Injection is a technique for supplying dependencies.
Dependency Inversion is a design principle that encourages high-level
and low-level modules to depend on abstractions.
15. What is the Repository Pattern?
It provides a consistent interface for accessing data and hides details
of the underlying data sources.
16. What is the Singleton Pattern?
It provides one shared instance within a defined scope. In Kotlin, an
object declaration creates a singleton object.
17. What is the Observer Pattern?
It allows observers to receive updates when a subject's state or data
changes. LiveData and Flow are commonly used for observable data streams
in Android.
18. What is the Strategy Pattern?
It encapsulates interchangeable algorithms behind a common interface,
allowing the behavior to be selected or replaced.
Advanced and scenario-based questions
19. Why should a ViewModel not hold an Activity reference?
A ViewModel can outlive an Activity instance during configuration
changes. Holding the old Activity can retain its view hierarchy and
cause memory leaks. Keep UI references in lifecycle-aware UI components.
20. Where should validation logic be placed?
It depends on the validation. Basic input feedback can live in the
presentation layer, while business-critical validation must be enforced
in the domain or appropriate business boundary. The backend must also
validate untrusted input.
21. Should every repository have an interface?
Not necessarily. Use an interface when it provides a meaningful
boundary, such as separating domain logic from data implementation or
enabling alternative implementations and testing. Avoid abstractions
that add no value.
22. What happens if a ViewModel becomes very large?
Identify separate responsibilities and extract meaningful collaborators,
such as use cases or focused components. Keep screen state coordination
in the ViewModel rather than moving code arbitrarily.
23. How would you design an offline-first Android application?
Use a local database as the UI's source of truth, observe local data
through Flow, coordinate remote synchronization through a repository,
and define retry and conflict-resolution policies.
24. How do you unit-test a ViewModel?
Inject dependencies, provide fake or mock implementations, execute
coroutine work with a test dispatcher, and assert the emitted UI state.
Avoid requiring an Activity or emulator for ordinary ViewModel unit
tests.
25. How do SOLID principles improve Android development?
They encourage focused classes, extensible behavior, safe abstractions,
smaller interfaces, and reduced coupling. This makes features easier to
test and change.
26. Is Clean Architecture mandatory for every Android application?
No. Architecture should match the application's complexity and expected
lifetime. A small app may not need separate modules and many use cases.
Larger applications benefit from stronger boundaries.
27. What is the difference between UI State and UI Events?
UI state describes information that should remain represented on the
screen, such as loading, content, or an error message. UI events are
actions or one-time effects, such as navigation or showing a transient
message. Event handling should account for lifecycle and delivery
requirements.
28. How would you choose between MVVM and MVP for an existing
project?
Consider the current architecture, testing needs, lifecycle handling, UI
framework, team experience, and migration cost. Avoid rewriting a stable
application solely because another pattern is more fashionable.
13. A practical learning roadmap
If you are learning or preparing for senior Android interviews, follow
this order:
- OOP fundamentals: Classes, objects, inheritance, polymorphism, abstraction, and interfaces.
- SOLID principles: Understand each principle and refactor small Kotlin examples.
- Design patterns: Practice Repository, Factory, Observer, Strategy, Builder, and Dependency Injection.
- Presentation patterns: Build the same small login feature using MVC, MVP, and MVVM.
- Android Jetpack: Learn ViewModel, StateFlow, lifecycle-aware collection, Room, Navigation, and coroutines.
- Clean Architecture: Separate presentation, domain, and data responsibilities.
- Testing: Write unit tests for use cases, repositories, and ViewModels.
- System design: Study offline-first behavior, caching, synchronization, modularization, scalability, and failure handling.
Practice project
Build a small Task Manager application with these features:
- Login and user session management.
- Create, update, and delete tasks.
- Task list with filtering and sorting.
- Room database for offline access.
- Retrofit or Ktor for remote APIs.
- Repository and use case layers.
- MVVM with StateFlow.
- Koin or Hilt for dependency injection.
- Unit tests for use cases and ViewModels.
Start with one feature and keep the design simple. Add complexity only
when a real requirement needs it.
14. Final thoughts
MVC, MVP, and MVVM are approaches to organizing presentation logic.
Clean Architecture helps define boundaries and dependency direction.
Design patterns offer reusable approaches to recurring problems, while
SOLID principles guide the design of maintainable object-oriented code.
For modern Android development, MVVM combined with clear domain and data
boundaries is a practical choice. However, the goal is not to follow a
particular architecture diagram. The goal is to build software that is
understandable, testable, reliable, and easy to change.
Remember: Good architecture is not the architecture with the most
layers. Good architecture is the simplest structure that handles today's
requirements while allowing tomorrow's changes.
Further reading
- Guide to app architecture --- Android Developers
- Recommendations for Android architecture
- Kotlin documentation
- Guide to app architecture --- Android Developers: UI layer
If you want to see these patterns in real code, my open-source Android projects are on GitHub.
About the author: Padmakar Garg is a Senior Android Developer with 8+ years of experience in Kotlin, Jetpack Compose, Kotlin Multiplatform and mobile security. Portfolio and blog: gargpadmakar.github.io. Connect on LinkedIn.
Top comments (0)