Shannon's Blog

.NET dev, going mobile

Model-View-ViewModel

As a consultant focused in the WPF and Mobile development spaces I've spent a lot of time in the world of MVVM. I've seen lots of different frameworks and lots of different ideas around implementing MVVM.

One thing that I've seen frequently cause confusion is the first M. To help explain that statement, here are the typical ways I try to describe MVVM to people.

What is MVVM?

Model-View-ViewModel. That's what it's short for.

MVVM is an adaptation of MVP and MVC, adjusted to play to the strengths of XAML's binding abilities.

It also abstracts the visual behaviour away from the View and into a ViewModel, which is just a class at the end of the day, and in doing so it becomes possible to unit test the visual behaviour without an actual UI.

What is a Model?

A Model represents data. The data may be a single entity, it might be an aggregate of multiple model entities. Its responsibility is to hold the data and notify others when changes occur. It is the Domain Model of your client app.

A model object instance may be shared between ViewModel instances.

What is a View Model?

A View Model represents the visual state of the data, and encapsulates the visual behaviour around that data. It may project the data stored in a model (e.g. FullName may project "Surname, FirstName"), but it's responsibility is to hold the transient, visual state of the data. IsSelected, IsChecked, IsEnabled, SelectedItem are examples of the types of properties on a ViewModel, they are not persisted but are important to the visualisation of the data.

A ViewModel type may be shared between Views, but here be dragons. Only do this if the visual behaviour required is identical. If it isn't identical then you will be tempted into adding multiple personalities to the ViewModel, and violating the "Single Responsibility" principle.

What is a View?

A View presents the data to a user, through the use of ViewModels and Models. A View can use a Model directly, if there is no requirement for visual state.

A View may also consist of sub-Views.

Don't forget the first M!

So back to my earlier statement, many implementations I've seen have lots of Views and ViewModels, but not a Model in sight. The first M (Model) gets neglected.

When you dig deeper there usually are Models, but they've been called ViewModels. How does the code get to this point? I think it's often that the pattern is not well understood and the team get into the habit of just calling everything a ViewModel, then they start sharing something called a ViewModel (but is actually a Model) between Views, then they get into the habit of doing that, then they start sharing ViewModels that really are ViewModels between Views, then the dragons...

So please, take the time to think about the first M, and avoid confusion by calling things what they actually are.

comments powered by Disqus