Friday 23 May 2014

MVVMC thought experiment

Who doesn't love MVVM right? Nice levels of abstraction and a simple binding model. Most of my MVVM experience has been with WPF and it’s been fun. However I have noticed an irritating trend where View Models tend to become bloated. The View is the view, the Model is clean (or should be) but the View Model becomes a bit of a dumping ground. Everything from loading the Model(s), manipulating the Model, business logic, interacting with services and repositories, validation, etc. It all adds up.

Bring in MVVMC. Now I thought I was being really original by coming up with this all on my own. Then I turned to trusty Google and surprise, surprise, it’s already a thing. It’s really hard to be original these days. The C stands for Controller and it’s where we want to move all the code that is not View Model specific. So to my mind you get this:


Now your View Model becomes squeaky clean. But haven’t we just moved our dirt from the View Model to the new Controller? Yes, but not really because you've moved it to a class that specifically exists to contain loading and logic for the View Model. It’s all in one place but now it’s the right place. You've increased the cohesion of your classes. Happy days!

As I see it a Controller could be shared by multiple View Models (if they’re part of the same component and share functionality). As an example, imagine you have a grid of data. You could structure it as a parent View Model with multiple child View Models and each child View Model wraps a Model. If every View Model knows about the Controller then parent and child need to know nothing about each other (except for the parent View Model having a collection of the child View Models) but both still have access to any logic in the Controller. This could be handy if say you want a Command on the parent that acts on all children and a Command on the children that only acts on itself. It would be one method (possibly overloaded) on the controller.



Two final thoughts. It makes sense to have your Controller as the starting point. So you create the Controller and that hydrates itself with View Models. It comes in very handy to have a Factory class that creates the View Models that can be injected into the Controller. With all of that you should be able to do something along the lines of Resolve<MyController> and as long as you've exposed your View Model on the Controller you're golden.



No comments:

Post a Comment