First a little background on MVVM…
MVVM (Model, View, ViewModel) is a pattern for separating logic from Silverlight XAML pages (the UI).
- A View is simply a UI page. It does not know where the data is coming from.
- A ViewModel holds a certain shape of data, and commands, that a View binds to.
- The model refers to the actual business data, which is used to populate the ViewModels.
The main benefit is that a XAML/UI designer can edit the look and feel of UI pages while a Silverlight developer makes them work, without them constantly tripping over each other. This is a good thing.
The problem we see with MVVM…
The problem with MVVM, as it stands, is that we see lots of people trying to cram their business logic into the ViewModel. Having so much app logic, in what is basically a storage box, does not make unit testing easy. In fact it makes it a lot more difficult. This feels like a bad fit. In code-speak, the pattern just “smells wrong”.
Then a light went on…
While trialing an application generation package, called Sculpture, we noticed it generated code for a number of platforms and in all cases it kept the application logic in separate controller classes. That included its MVVM style code for Silverlight and WPF. This seemed like an interesting idea, so we investigated further and applied the idea to a few of our own projects. The results not only felt good but that bad-code smell evaporated
The basic MVCVM mantra:
- ViewModels are just dumb containers that hold a certain shape of data: “They do not know where the data comes from or where it is displayed”.
- Views display a certain shape of data (via bindings to a view model): “They do not know where the data comes from, only how to display it”.
- Models supply real data: “They do not know where it is consumed”.
- Controllers implement application logic. “The listen and broadcast messages/events”.
Controller supply the code for ICommands in VMs, listening for changes to data etc.
Controllers populate VMs from Models.
Controllers listen for VM changes and update the Model.
Basically Controllers become the glue that hold complete independent components together and turn building blocks into applications.
“Long live controllers!” – This series will be updated with examples soon…