Home > Net >  Separation of Concerns in MVVM
Separation of Concerns in MVVM

Time:09-28

I am working on understanding MVVM better, and from trusty Wikipedia (and lots of other research), I have gathered that the ViewModel holds presentation logic and the Model holds the business logic.

MVVM Pattern (Image courtersy of Wikipedia)

My question is, how is there a separation of concerns between logic and data when the Model is holding the business logic? Why is this a good pattern and why would I want to use it instead of using MVC where the Controller handles business and presentation logic (if I understand it correctly)? (I am using WPF, which based on my research, mainly uses MVVM and rarely uses MVC, and I still don't understand why).

CodePudding user response:

Let's get some things straight:

MVC = Model View Controller

MVVM = Model View ViewModel

With MVC, the controller controls the data and the business logic, the model stores the data temporarily, and the View can read the data from the model. In this model, the View handles the presentation logic. In C#, you can use Razor Pages (.cshtml) to dynamically insert values into the view.

MVVM is very similar. The Model is responsible for holding the data and business logic, the View Model holds the data temporarily, and the View controls the presentation logic. The main difference is the physical separation in your code.

With MVC, each step is separated into its own file. With MVVM, usually two or more steps are combined together into one file. This can be advantageous because it keeps you from having controllers that are hundreds or thousands of lines long if you have lots of pages. I personally still like MVC, because it keeps everything separate instead of combining it together.

CodePudding user response:

Separating presentation logic from business logic allows you to change business logic without directly affecting presentation logic.

For example, if you have a RESTful web API that retrieves some data a view should render, the ViewModel should not be directly handling the HTTP operation or any translation of the incoming data. The ViewModel should ask a (separated) service class to retrieve that data and then the ViewModel can choose how to present that data, such as by pagination, sorting, filtering, and so on. You may choose to paginate at the web API level instead, but that's an implementation detail. In the event that your API contract changes, you can change the web API service without affecting the presentation logic: separation of concerns.

  • Related