If I have a Viewmodel designed to serve a purpose for a view -
Is it a good practice to add bunch of static methods to the viewmodel like - getting a list of items(viewmodel object) by consuming data from db? - updating the db using a property in the viewmodel?
I am using .NET MVC and feel like my viewmodels get cluttered with bunch of static functions and update methods.
The main reason behind creating viewmodel for the views was because the views started to contain a lot of functionalities for which info had to be fetched from all over the place. So instead, i decided to create a viewmodel to get the info from one place with one call.
Am I following a good coding pattern here? Or am I shooting in the dark?
At least in my knowledge, as per the design principles, ideally we should not have methods in view model classes and create a separate class to manage interaction between business objects and view models.
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.
Static objects and everything they reference will never be garbage collected. Example: Any instance of Static will forever stay in memory, causing a memory leak.
ViewModel objects are designed to outlive specific instantiations of views or LifecycleOwners . This design also means you can write tests to cover a ViewModel more easily as it doesn't know about view and Lifecycle objects. ViewModel objects can contain LifecycleObservers , such as LiveData objects.
Is it a good practice to add bunch of static methods to the viewmodel
No, your viewmodel should simply be a POCO, containing as little (if not zero) business logic. A view models only job is to move data from the controller to the view.
If you read the wikipedia page for the MVC pattern. You'll notice it is solely designed for the presentation of data, not business logic:
Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces.
so really none of the MVC objects (Model, View or controller) should contain business logic. The MVC patterns job is to render data (full stop)
That all said it is common to put simple business logic into the controller. Once sites get more complex, though, this should be avoided, for fear of creating a god object
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