I'm using XamarinForms, and Prism for MVVM with Unity as my IoC container.
I'm refactoring a tonne of duplicate View and ViewModel code that a previous employee worked on. What they've done is essentially cut and paste a massively complex View and ViewModel. I needed to change some things in these, and had to do it 5 times because of this spaghetti code. This is basically what the view looks like:
The 5 instances of these CardViews and their different Viewmodels have a main title, 3 labels and 3 values that go with the labels. The values are retrieved using various restful calls (all using various parameters to retrieve them and processing the results of the calls too).
My question is, what patterns should I be using to simplify these 5 Views and ViewModels, preferably into only 1 file that I need to change? Roughly speaking, I think I should have a ViewModel that offers all of the text, values and functions that I require to get this remote data. But I'm scratching my head at all the different approaches that it seems are available to me (ViewModel interfaces, dependency injection, methods of registering the template view with different instances of the same ViewModel, etc).
What complicates my problem in particular is that these 5 different views are split across Prism Modules (i.e. .NET projects). I understand the need for these but they seem to just add to the problem of duplicate code that largely does the same thing. Maybe these should contain the logic for the restful calls and processing? But how would that fit in with my ViewModel/View association problem from above?
I will continue researching the best way to do this, but I just wanted to know if anyone can steer me into the best practice direction?
If you have five views that look the same and five view models that do (nearly) the same thing, drop four of each. To account for the differences in the view models perform, create services.
The BookService
might implement GetTitles
by querying a rest service for book titles while the DvdService
queries another rest service for dvd titles. Both of them implement ITitleService
. Then the UnifiedViewModel
is specialized for books by passing it a BookService
(preferably through constructor injection) and thus it does exactly what the BookViewModel
did before. Just now you have one view model and five services where before you had five view models.