Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build the ViewModel in MVVM not to violate the Single Responsibility Principle?

Robert Martin says: "There should never be more than one reason for a class to change".

Let's consider the ViewModel class which is bound to a View. It is possible (or even probable) that the ViewModel consists of properties that are not really related to each other. For small views the ViewModel may be quite coherent, but while the application gets more complex the ViewModel will expose data that will be subject to change for different and unrelated reasons.

Should we worry about the SRP principle in the case of ViewModel class or not?

like image 730
Przemek Avatar asked Feb 27 '09 21:02

Przemek


People also ask

What is the ViewModel responsible for?

ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment . It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).

What is the use of ViewModel in MVVM?

ViewModel interacts with model and also prepares observable(s) that can be observed by a View. ViewModel can optionally provide hooks for the view to pass events to the model.

Is single responsibility principle a design pattern?

The single responsibility principle is one of the most commonly used design principles in object-oriented programming. You can apply it to classes, software components, and microservices.


2 Answers

The ViewModel single responsibility is to provide the View the information it needs. If the View needs different and unrelated properties that is not important as the ViewModel only has one reason to change and that is the View showing different properties. So you shouldn't worry too much.

That said, if the ViewModel does get huge, maybe you could think about dividing the view into several subviews to improve reusability and keep the Views and the ViewModels manageable.

like image 68
gcores Avatar answered Sep 23 '22 10:09

gcores


I agree with gcores.

Once you see ViewModel grow to more than two screenfuls of text, it is time to consider splitting ViewModel into several child models.

Another rule of thumb is that I never have more than two levels of nesting inside XAML file -- if one part of the view becomes too complex, it is time for view refactoring -- extract inner XAML into separate UserControl and create corresponding ViewModel, which will be default data context on child view.

like image 22
Srdjan Jovcic Avatar answered Sep 23 '22 10:09

Srdjan Jovcic