Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a view model contain logic?

Tags:

mvvm

wpf

In a wpf application, Whats the responsibility of the viewmodel? can he manage everything or only represent the view and send messages/event to the business layer and get information from it?

like image 522
Chen Kinnrot Avatar asked Jan 06 '11 05:01

Chen Kinnrot


People also ask

Does a ViewModel contain logic?

A ViewModel object provides the data for a specific UI component, such as a fragment or activity, and contains data-handling business logic to communicate with the model.

What should ViewModel contain?

View Model: It encapsulates the presentation logic required to support a use case or user task in the application. The view model is testable independently of the view and the model. The view model typically does not directly reference the view. It implements properties and commands to which the view can data bind.

Where should business logic reside in MVVM?

In MVVM, the business logic is built into the Model. The ViewModel is there to bridge between the View and the Model, so it's logic only pertains to driving the display and updating the model from user interactions with the View.

What is the point of a ViewModel?

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.


1 Answers

Short answer, Yes.

Longer answer ...

The main aims of the Model-View-ViewModel (MVVM) pattern are:

  1. Permit unit testing of your view logic. These are unit tests applied to the ViewModel layer which is executed without a View associated with it.
  2. Facilitate developer-designer workflow by minimising the amount of code-behind associated with your XAML files.

The MVVM pattern also provides separation of concerns between view logic and business logic in the same way that the MVC and their UI pattern do. However, the 2 points above are what really define the MVVM pattern.

Now, thinking about where you locate your business logic. If you place it in your ViewModel, are #1 & #2 above still valid? Yes. If you place it in a separate layer, are #1 and #2 still valid? Yes.

Therefore, in both cases you are still achieving the two main goals of MVVM. Which route you take really depends on the complexity of your application, and the number of developers working on it. As both these factors increase, you will benefit from having 3 layers ... or more!

like image 164
ColinE Avatar answered Oct 08 '22 02:10

ColinE