views:

34

answers:

2

Having used ViewModels in MVC, I was wondering if applying the same to the MVP pattern is practical. I only have a few considerations, one being that MVP is already fairly hard to implement (with all the additional coding, not much on the seeming complexity) or that ViewModels already have a slightly similar way of modeling data or entities. Would adding another layer in the form of ViewModels be redundant or is it a logical abstraction that I, as one implementing the MVP pattern, should adhere to?

A: 

Found a MVPVM implementation that is similar to what I wanted to do. (Found it to be very complex when I implemented it though. Lots of repetitive work. Probably will be better with a code generation tool)

Jonn
+1  A: 

ViewModels can be very useful in MVP, and I think add more benefit than the cost of extra coding.

I think the guiding rule is to use them where you need them, not simply to add more patterns or architecture for their own sake.

I work on a decent sized public facing asp.net web application, but the following applies to MVP in WinForms as well. Below are the reasons I found to use VM in MVP.

The site aggregates data from a boatload of LOB web services. The services are maintained by various development groups in different business verticals. The data coming back is all over the place in terms of:

  • Type Soup - Storing GUIDs as strings, returning doubles instead of decimals, dates as strings, etc
  • Crazy Naming Conventions - Camel case properties, underscores in names, abbreviation jumbles

But the biggest reason I found to use it was the model provided was the same as in MVC: the models just didn't fit the shape of the views. We are combining model classes and adding extra fields for calculations or aggregated values, etc.

In terms of changes we made we had to:

  • Create a new ViewModels folder along side the Views and Presenters (Controllers) folder
  • Map the model values to the view model
  • Change the property on the view interface from a model type to a view model type
  • Implement the view according to the new object

The only time consuming part of this is naturally the mapping of the model(s) to the view model. In our case we are forced to do a decent amount of processing in our presenters to get the data we need that assigning properties is not a big deal. For simpler needs something like AutoMapper would remove this pain for mappings.

blu
A few months of trial and error made me think of using VMs on a case to case basis. It does simplify a great deal of work when it comes to wrapping models so changes can be adjusted easily. Instead of mappers though, I use them as a wrapper to simplify things.
Jonn