100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
.NET

MVVM Best Practices

Practical guidelines for structuring ViewModels, bindings, and data flow so MVVM code stays maintainable at scale.

Practical MVVMIntermediate9 min readJul 10, 2026
Analogies

Keep ViewModels Thin and Focused

Each screen or feature should have exactly one ViewModel with a single, clear responsibility: orchestrating calls to the domain layer and exposing the resulting UI state. Business rules — how a discount is calculated, whether a form field is valid — belong in use-case or domain classes the ViewModel calls into, not inline inside the ViewModel itself. This keeps each class small enough to read, test, and reason about in isolation.

🏏

Cricket analogy: It's like a team having a dedicated fielding coach, batting coach, and bowling coach instead of one person trying to own every specialist skill, so each area gets focused expertise.

Expose Immutable State, Mutate Internally

A ViewModel should expose read-only observable state to the View — a StateFlow via asStateFlow(), a LiveData without a mutable setter visible externally, or a SwiftUI @Published property behind a protocol — while keeping the mutable backing field private. This enforces unidirectional data flow: the View can never illegally mutate state directly, it can only trigger a command that asks the ViewModel to update state on its behalf.

🏏

Cricket analogy: It's like only the official scorer being allowed to update the scoreboard, while players and spectators can only request a review, not touch the numbers themselves directly.

kotlin
class LoginViewModel(private val authRepo: AuthRepository) : ViewModel() {

    private val _uiState = MutableStateFlow(LoginUiState())
    val uiState: StateFlow<LoginUiState> = _uiState.asStateFlow()

    fun onLoginClicked(email: String, password: String) {
        _uiState.update { it.copy(isLoading = true, error = null) }
        viewModelScope.launch {
            val result = authRepo.login(email, password)
            _uiState.update {
                it.copy(isLoading = false, isLoggedIn = result.isSuccess,
                    error = result.exceptionOrNull()?.message)
            }
        }
    }
}

Use Dependency Injection

Dependencies such as repositories and use cases should be injected through the constructor using a DI framework — Hilt or Koin on Android, Dagger, or the built-in DI container in ASP.NET/.NET applications — instead of the ViewModel instantiating them itself with new or a singleton call. Beyond enabling testability, this gives a single, consistent place to manage object lifecycles and scoping, rather than each ViewModel improvising its own object creation strategy.

🏏

Cricket analogy: It's like a franchise having a dedicated team-management staff assign players to a squad through an official contract process, rather than each player independently deciding to show up and play.

Aim for a single source of truth for every piece of UI state. If the same information (say, 'is the cart empty') can be derived two different ways in two different fields, they will eventually disagree — derive it once and expose it, rather than storing duplicated flags.

Model UI State as a Single State Class

Rather than exposing several independent booleans like isLoading, hasError, and hasData, model the screen's state as one sealed class or state data class with mutually exclusive variants (Loading, Success(data), Error(message)). This makes impossible combinations, such as isLoading being true at the same time as hasError being true, unrepresentable at the type level, which the View's when/switch exhaustiveness check enforces at compile time.

🏏

Cricket analogy: It's like a match status field that can only ever be one of 'In Progress', 'Rain Delayed', or 'Completed' at a time, rather than three separate independent flags that could contradict each other.

Avoid putting real business logic inside XAML value converters or platform-specific View helpers just because they're convenient to reach for. Converters should perform pure presentation formatting only; anything that decides application behavior belongs in the ViewModel or a dedicated formatter/use-case class where it can be unit tested directly.

  • Give each screen exactly one ViewModel with a single responsibility: orchestrate calls and expose UI state.
  • Expose read-only observable state (asStateFlow, LiveData, @Published behind a protocol) and keep mutable backing fields private.
  • Inject dependencies via constructor and a DI framework rather than instantiating them inside the ViewModel.
  • Maintain a single source of truth for each piece of state to avoid duplicated, conflicting fields.
  • Model UI state as one sealed class/data class with mutually exclusive variants instead of several independent booleans.
  • Keep business logic out of XAML converters and platform View helpers; keep it in the ViewModel or domain layer.
  • Favor unidirectional data flow: View triggers commands, ViewModel updates state, View re-renders from that state.

Practice what you learned

Was this page helpful?

Topics covered

#NET#MVVMDesignPatternStudyNotes#MicrosoftTechnologies#MVVMBestPractices#MVVM#Keep#ViewModels#Thin#StudyNotes#SkillVeris