Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I implement business logic on a Model or a ViewModel

Tags:

c#

mvvm

When I'm processing business logic in an MVVM app. Should I do this on the Model or the ViewModel?

For example, if I want to re-calculate costs after an Asset has been re-valued, should I operate on the Model?

Is there an advantage in doing this on the ViewModel instead?

What happens if I have a list of ViewModels, but I want to translate that into a list of Models so I can do some processing? I could expose the Model as a property of the ViewModel (and use that to build the list of Models). But that means that the View will be able to access properties of the original Model

like image 1000
Mitkins Avatar asked Jun 07 '16 06:06

Mitkins


People also ask

Should ViewModel contain business logic?

ViewModel: ViewModel is the middle layer between the view and model. ViewModel contains the business logic, which manipulates the row data to show in the view. Any kind of function and methods should be in the view model.

Where should business logic reside in MVVM?

In MVVM, the business logic is built into the Model. The ViewModel is there to bridge between the View and the Model, so it's logic only pertains to driving the display and updating the model from user interactions with the View.

Should ViewModel know about model?

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.

What is the purpose of a ViewModel?

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.


1 Answers

The Model's purpose is to represent (or model) your business domain. Therefore, business logic by definition goes in the Model, not the ViewModel.

The job of the ViewModel is to expose properties and fields of the Model, and prepare them for consumption by the View.

For instance, picture a banking application. The Model may represent an account. Perhaps the Model has an account balance. The job of the Model may be to track the balance and make sure certain invariants are maintained (such as not allowing a withdrawal that is larger than the balance). The job of the ViewModel may be to turn the balance into a string that is used as a binding in the View.

You want to keep as much logic out of the ViewModel as possible to keep your code reusable and loosely coupled.

like image 143
bodangly Avatar answered Sep 21 '22 17:09

bodangly