I'm working on a WPF application, and I'm structuring it using the MVVM pattern. Initially I had an idea that the ViewModels should be reusable, but now I'm not too sure anymore.
So; should one write ViewModel classes with one specific View in mind, or think of reusability?
Models are just the plain data, and a ViewModel is something that acts like a padding in between the two, that it should get information from the Model and pass it onto the View, and the View should know how to present it.
It is perfectly right to have ViewModel contains ViewModel. Actually that is the recommended practice: To have one main ViewModel for the whole page, the main ViewModel could contain ViewModels for the sub views in the page.
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.
To answer your question, think about Single Responsibility Principle:
"A class should have one, and only one, reason to change."
I'd say, within reason, you typically don't want to reuse a ViewModel for multiple views. The main reason I'd argue for this, is because that would give your ViewModel more than one reason to change. In other words, it'd need to change if one or the other view changes, and in my opinion, that's two reasons to change. Where does it stop? I'd keep it simple in this case, and bind one ViewModel to the View.
Another thing to think about with MVVM with WPF is Data Templating. It's much easier to accomplish if each ViewModel caters to one and only one view.
Just in general, apply the YAGNI principl - you probably aren't going to need it. Unless you can see these things as potentially happening, I'd keep with the simplest approach to get your software working for the requirements you currently have.
In my mind, the main goal of MVVM is to eliminate code that cannot be easily tested by unit tests. Since a view model can be unit tested but a view cannot, this is achieved by making the view as dumb as possible. Ideally, as can be done with XAML, the view is completely declarative and only data-binds on a view model. Hence the "no code behind" mantra.
Re-usability of the view model across different UI technologies is not really a goal of MVVM. If you try it you will probably be tempted to move code specific to the UI technology to the view again to keep the view model reusable. This would go against the main goal of testability.
If you really find yourself needing to support different UI technologies, then you could still factor out the common logic of the view models into a shared "presentation" layer. I wouldn't do that until sure that it is necessary though.
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