MVC – How Closely Coupled Are Model and View to Controller?

mvc

I've got an app which uses MVC, but I'm struggling a little as to how the controller should be architected. For example, the View is only viewing some subset of the model's data at once. However, I'm unsure as to exactly how this should be arranged. Is it normal for the View or Model to directly call functions on the Controller, for example? Through some sort of interface? Or are they totally encapsulated and never know about the Controller or each other?

Just as an edit; this is a custom app not written in any web framework, so I'm not looking for framework-specific details here and have the freedom to make my own choice.

Best Answer

The controller controls the flow of activity. The user performs this action, the controller passes the view data to the domain which does whatever it needs to do then, based on the response(s), the controller tells the framework which view to show next (and gives it enough data to do so).

The controller must thus be coupled to the domain model, to some extent. ie. You could put a service layer in between but, by strict definition, that becomes part of the domain.

It is also coupled to the view data but not the view itself. ie. it simply says "show the customer view using this customer detail." The framework then decides where it should find that view.

Now this should allow you to decouple the domain model from the view, by using a view model of the same data. Some developers do this, some don't, and I do think it's largely a matter of personal preference.

In Rails, you are very much encouraged to push the domain objects (ActiveRecord) to the view and trust that the view doesn't take advantage of that access (eg. you shouldn't call customer.save from the view, even though it would be available).

In the .NET world, we tend to reduce risk by not allowing things that shouldn't happen and, possibly for that reason, it seems to me that the detached view model is more popular.

Related Topic