Should I implement business logic on a Model or a ViewModel

后端 未结 4 715
走了就别回头了
走了就别回头了 2021-01-04 11:28

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 b

相关标签:
4条回答
  • 2021-01-04 11:57

    Use the model if you are building a web app; and one level bellow the model i.e. the domain level if you are building a LAN/desk app.

    Your problem - re-calculate costs after an asset has been re-valued - might not just be a user interface issue. A back-end application might want to do the same (for example, for automatically importing data). And then you have a choice of either duplicating business logic or rewiring to existing one.

    Nothing wrong with using the same model for the back-end too. But models -especially disconnected ones- tend to be large data structures because they need to bring with them all data from reference tables (unless you want to do round trips to server and sacrifice your GUI experience). And that might affect performance if model is used.

    0 讨论(0)
  • 2021-01-04 12:03

    if you model contain required data for calculation you can use model.if model does not contain the data means create view-model and get data to do the calculation.(With respect to Business logic )

    if you want to pass this data to view create View Model It improves code re-use opportunities

    0 讨论(0)
  • 2021-01-04 12:16

    My suggestion is to put logic in a service layer instead. This is a middle layer between view model and model (which, in a real object oriented paradigm, should only contains properties). So the correct life circle may be: View model -> service -> model handling. This allows also to reuse business logic code through others view model if needed

    0 讨论(0)
  • 2021-01-04 12:17

    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.

    0 讨论(0)
提交回复
热议问题