Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a ViewModel and Controller?

What are the responsibilities of one vs the other? What kind of logic should go in one vs the other? Which one hits services and databases? How do I decide if my code should go in the viewmodel or the controller?

For the record, I am using ASP MVC, but since the question is architectural, I do not believe it matters what language or framework I am using. I'm inviting all MVC to respond

like image 716
MedicineMan Avatar asked Dec 11 '09 21:12

MedicineMan


People also ask

What is the difference between ViewModel and model?

A model is usually more closely related to how your data is stored (database, services, etc.) and the model will closely resemble those. The ViewModel on the other hand is closely related to how your data is presented to the user. It is usually a flatten version of your model, denormalized, etc.

What is the purpose of a ViewModel?

The purpose of the ViewModel is to acquire and keep the information that is necessary for an Activity or a Fragment. The Activity or the Fragment should be able to observe changes in the ViewModel. ViewModels usually expose this information via LiveData or Android Data Binding.

Does MVVM have a controller?

Another benefit of the MVVM pattern is improved testability of controllers. Controllers no longer interact with the model layer, which makes them easier to test.

What is difference between MVVM and MVC?

Whereas the MVC format is specifically designed to create a separation of concerns between the model and view, the MVVM format with data-binding is designed specifically to allow the view and model to communicate directly with each other.


1 Answers

The ViewModel is a Pattern used to handle the presentation logic and state of the View and the controller is one of the fundamentals parts of any MVC framework, it responds to any http request and orchestrates all the subsequent actions until the http response.

The ViewModel Pattern: More info

In the ViewModel pattern, the UI and any UI logic are encapsulated in a View. The View observes a ViewModel which encapsulates presentation logic and state. The ViewModel in turn interacts with the Model and acts as an intermediary between it and the View.

View <-> ViewModel <-> Model 

The Controllers (Comes from the Front Controller Pattern): More Info

It "provides a centralized entry point for handling requests."

HTTP Request -> Controller -> (Model,View) 

--Plain Differences:--

  • While the ViewModel is an optional pattern the Controller is a must, if you are going the MVC way.
  • The ViewModel encapsulates presentation logic and state, The Controller orchestrates all the Application Flow.
like image 184
JOBG Avatar answered Oct 07 '22 16:10

JOBG