Mvc – Should a view and a model communicate or not

designmvc

According to the wikipedia page for the MVC architecture, the view is free to be notified by the model, and is also free to query the model about its current state. However, according to Paul Hegarty's course on iOS 5 at Stanford, lecture 1, page 18 all interaction must go through the controller, with Model and View that are never supposed to know each other. It is not clear to me if Hegarty's statement must be intended as a simplification for the course, but I am tempted to say that he intends the design as such.

How do you explain these two opposite points of view ?

Best Answer

This is a controversial topic in MVC/MVVM. Some say it is OK for the View to access the Models directly, other say you should wrap the Models in ViewModels in order to abstract them away from the View. I'm personally not a fan of either approach.

The one of the primary goals of MVC/MVVM is to decouple the UI, business logic and data. So with that concept in mind, allowing the View to directly access the Models creates a dependency that you might not want to have. On the other hand, wrapping the Models in ViewModels is often tedious and not very useful as the ViewModels tend to act simply as a pass-through to the Models.

I like the approach of having your Models implement a particular interface, lets call it IModel. Your ViewModel class can then offer instances of objects that implement IModel for View consumption. The View simply knows it works with IModel objects that it gets from the ViewModel. This removes the extraneous ViewModel wrapper code as well as hides the concrete implementation of IModel from the View. You can later swap out one implementation of IModel for another without affecting the View one bit.

Related Topic