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?
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With