开发者

Can I just enhance the Model instead of building a ViewModel?

开发者 https://www.devze.com 2023-03-04 04:30 出处:网络
I know that mvvm calls for having a ViewModel class that wraps a Model class, but I\'m wondering why it\'s a better practice to do this rather than just enhancing the Model class directly via partial

I know that mvvm calls for having a ViewModel class that wraps a Model class, but I'm wondering why it's a better practice to do this rather than just enhancing the Model class directly via partial classes. I get that you might want the Model to be auto-generated from an ORM, but you can still put the开发者_运维问答 ViewModel stuff in another file via a partial class, and doing this avoids the considerable overhead of maintaining a ViewModel for every Model. So I guess the question is: what's so bad about letting the Model have UI oriented code, as long as you separate it in the source code and don't use the UI aspects of the Model inappropriately?


The point is separation of concerns. Your ViewModel is built specifically for the needs of the UI; that means the data it contains is formatted specifically for the UI, whereas your Model is formatted directly for your persistence or domain logic.

In your situation, changing your model necesarily requires then that a change is also done to the view model; when separated, each can vary independently which reduces unintended side effects.


what's so bad about letting the Model have UI oriented code, as long as you separate it in the source code and don't use the UI aspects of the Model inappropriately?

Nothing if you have a complete set of unit tests and are willing to update all locations that are using your model if it changes, or if you can guarantee that your database will never change.


You can't really "enhance" your Model instead of using a viewModel. In theory you could, but it would be very bad code. Just a simple example: Imagine that you have a class User with only 2 fields: userName and password. This User class is your model. But on your page you want to add one more field to edit/add the data: the password verification field. So are you going to add password2 field into your User class? That's bad! Instead you better create a ViewModel binded to your View and based on the data of your ViewModel then you create the instance of your Model and process it in the other layers

0

精彩评论

暂无评论...
验证码 换一张
取 消