robertl
robertl

Reputation: 69

In Model-View-Controller, is it ever okay for the view to depend on the model?

The literature on Model-View-Controller (MVC) generally states that the model and the view are mutually independent entities, whereas the controller mediates their interaction and thus strongly depends on both.

At a theoretical level, the last statement seems like a sound approach by which to enforce modularity.

But suppose you've written an application that allows users to create, edit, and save documents. More sophisticated than simple textual documents, these documents consist of multiple fields, not all of the same type. It then occurs to you that, in order to polymorphically support multiple visual representations of the same document, you could define a DocumentView interface, which any concrete view subclass could adopt to indicate that it's able to display a document.

Now, suppose you've written the SomeDocumentView class, which adopts the DocumentView interface. To create the document view, your application code would have a line similar to the one below:

DocumentView documentView = SomeDocumentView(document)

Now suppose in the future, you've written the UpdatedDocumentView class, which also adopts the DocumentView interface. To make that change, you'd just need to replace the line above with:

DocumentView documentView = UpdatedDocumentView(document)

Voila! Your application code automatically supports your UpdatedDocumentView through the DocumentView interface.

But doesn't such a design violate MVC, because the view's implementation now explicitly depends on the model? Why's that necessarily a bad thing? If your model changes in the future, you'll have to change code regardless of your approach.

Upvotes: 2

Views: 288

Answers (1)

Daniel T.
Daniel T.

Reputation: 33967

"Model View Controller" has meant different things at different times. In the original MVC, in Smalltalk, the controller represented user input, and yes, views took model objects and represented them directly.

Apple's MVC is more of an alias for MVP where, as you say, the presenter/controller acts as the middleman between the model and the view.

This pattern allows views to be developed independently. Likely in the case of your DocuentView it will actually be a composite and controller of several other views, thus blurring the distinction between view and controller.

One of the reasons UIViewController is called such is because it handles many of a views responsibilities, namely user input gestures. Using these features in modern code is generally frowned upon though. Apple provides more discrete mechanisms now.

Upvotes: 1

Related Questions