I am trying to understand the MVVM pattern and there is some issue that is not clear. My Xamarin Forms application will have several Views (which is quite obvious). Must everyone of them be binded to different ModelView class? Or maybe there should be only one MV?
Yes and No
Yes -> Basically the idea is that your ViewModel should only be used by one view. If you use a ViewModel to populate an area or whatever then that ViewModel is "reused" each time that view is presented in difference places.
No -> You can use multiple models in a view model. The purpose of the view model is to abstract away the business / data layer (i.e. the model).
However, using more than one model usually indicates that the view is too large. You might want to split it into user controls (which have their own view models).
References:
With MVVM, does each UI window have its own ViewModel?
In MVVM, is every ViewModel coupled to just one Model?
I've always thought of "each View has its own VM" - the model as being a sub-set of a comprehensive design.
I will say from painful experience: do not design models in isolation based solely on the view/UI they support. Without a comprehensive model back end you will have a hard time integrating all of the pieces into a coherent, complete business model that works. Anemic classes, redundant bits, incomplete and wrong validations, same properties-different names, incompatibilities w/ existing code, gobs of hacky glue code, Programmers breaking each other's code, no re-usability, no reuse of existing classes. For us it all came to a head in a 3 month test-fail-fix tilt-a-whirl of embarrassment.
Related
Recently, I'm learning MVVM design pattern!
In my way, I write the database function in the model, and let the viewmodel to call the database function in the model, then the viewmodel get database data and set to the viewmodel notfiypropertychanged. This is my way that I currently use!
There are some question confused me about model,
I read many article that told me model just a contain data and not more business logic, and here is my question, if model just a data container and I need to let my viewmodel to call the database then get data and set to the model, I think this way is very strange and the viewmodel code is make heavy in it. Is anybody have another method to do it? Thank you!
The Model:
"model just a contain data and not more business logic"
A model is a class which describe an entity within your domain logic. What is a domain? Starbuck's domain is coffee beverages and employees (among others), Ford's domain is cars, assembly lines, and employees. NYTimes's domain is articles, issues, supply routes, subscribers, etc, etc.
A model contains data AND logic. You can have multiple models to describe your domain.
You can place your data calls in your model, but it's more common to have helper classes, data access layers (DAL), keeping all your database calls in one place, and not spread them around.
The ViewModel:
The viewmodel sits between your domain model and your view. It's a class which expose properties of the model and represents the state of the view. The viewmodel may only exposes a subset of all the properties in the model that the UI needs to display, but it could also add properties of its own, for example; is the user in edit mode? have changes been made that needs saving? etc. The selling point with MVVM is that the UI binds to these properties on the viewmodel which is a mechanism to keep the UI up to date with changes, and this extra layer of abstraction conveniently decouples the view to any logic in your model making it more robust for code changes in either direction and testable. There's more to say on this topic, but I'll leave it to you to read on up it.
There are many good resources and info on the MVVM pattern; from blogs Model-View-ViewModel (MVVM) Explained, to Microsoft The MVVM Pattern and here on SO.
If you prefer videos, Pluralsight have good video tutorials on the MVVM pattern
Practical MVVM and WPF MVVM In Depths. They have a free 30-day trial.
"just a data container"
Such classes that only hold data to be passed around are often called Data Transfer Objects (DTO). It's common to keep them small and return collections of these from fetch database data method calls.
I've done some research in this and also found it quite confusing. First thing I like to point out is that code-patterns are abstract. Meaning that you have loads of different way to implement it / tweak it.
What most people have told me is that in "real-life" applications you usually have layers of services.
One of these services is where you get data from a database.
The Model job (in my opinion) is to give the developer knowledge about the database data and structure. One Model to one database-tabel.
It also helps in checking if the data is correct (Format checking, Type of data and so on) before sending it to the DB.
There isn't a clear answer on how to use model. I've seen loads of different implementations, and they all have been implemented for specific tasks.
Yes it might come out that some ViewModels become heavy-loaded with code and functions to perform, but then it might not be because of the code-pattern. It can be because of poor structure in code. At my work right now I've found a ViewModel that contained over 3000 lines of code (Which is WAY to much). This could easily be seperated into atleast 3 different ViewModels and Views, but as I said, poor code structure causes problem.
One thing I recommend for you to read up on is
IoC - Inversion of Control
DoP - Dependency inversion principle
DI - Dependency Injection
Hope this helps in someway explaining your question.
I read many article that told me model just a contain data and not more business logic
A model may be represented by a service, a database access layer or a business layer so there is nothing wrong with your current approach. The business logic does belong to the model.
But sometimes people tend to refer to a "child" type as a model. For example, if your view model exposes a List<Item> property, the Item class may considered to be a model. Perhaps your confusion comes from this.
This kind of classes (Item) typically implement the INotifyPropertyChanged interface to provide change notifications and are effectively rather just "nested" view models that don't contain any business logic though.
Hope that makes sense.
I know that in MVVM, we want to propagate user input from the view to the view model via data binding, and give the reflected view state in the view model to the model, where we write the business logic code, and update the user with the result via events.
However, does it mean that every change in the view must be done outside of the xaml.cs file?
Take for example a WPF application for sliding puzzle:
If we want to write an algorithm to solve the puzzle, we'll put the code in the model.
However, assume we want to update the grid after the user clicked the down key.
Checking if such move is possible, redrawing the board or giving the player any feedback (if the move is legit or no) should be done in the view? (the xaml.cs file)
More generally, are there "rules of thumb" to decide what to handle where?
Quick recap for the MVVM layers (or "rules of thumb"):
Model: Contains only the data used by the view models. As an exemple, consider business objects coming from database as "models".
View: Connection between the user and the view model. You can use multiple views for a same view model. If the view model changes and updates, the view should show the changes.
ViewModel: Contains the "business logic" between the view and the model. As such, commands, possible actions and algorithms are stored here. The view model dictates what is possible and what is not.
The communication between layers needs (that's the part necessary for MVVM) to be interchangeable, meaning the view model can be used with differents compatibles views and the model can be used by differents compatibles view models. To cut down on the dependencies of the multiples layers: the layers should not communicate directly between them. We use commands, events and direct bindings.
However, does it mean that every change in the view must be done outside of the xaml.cs file? [...] However, assume we want to update the grid after the user clicked the down key. Checking if such move is possible, redrawing the board or giving the player any feedback (if the move is legit or no) should be done in the view? (the xaml.cs file)
No. The view model should explicitly tell the view what is possible and what is not. The view shows that the action is possible or not: it does not decide if it is possible. Such decision is in the business logic, so in the view model.
As a trail of thoughts, take what it is said about interchangeable views. If you switch out the view foo for another view bar to show your puzzle and you did put the decision about "what's possible" in the view, you will have to rewrite the decision tree/algorithm in the new view bar and thus, duplication of code/logic.
When the decision is higher up, the view reflects what the view model is telling him. If the view model wants the view to "refresh" or to tell the user "hey, that's an illegal move", the view model will do so via commands and events. After receiving such events, the view could then decide what to do with it:
Show an error message about the illegal move
Show a tooltip that the move is illegal
Flash and shake the window with a beep to show that the move is illegal
Many more implementations...
I do hope I answered your question as thoroughly as possible.
My 10 cents:
If my experience have taught me anything, it's that it's almost impossible to fit all problems with the same, general solution.
In the case of MVVM, some things I've learned (the hard way):
It's easy for the view model to devolve into God classes (ie, mix of purely view-related logic + some business logic + etc..)
Depending on the application tiers, some times it makes sense for logic to work on view models; other times, it's better for logic to work on the models instead.
Whatever layers I/you/anyone think certain classes/logic should go, will most likely have to change as development progresses.
Instead, my approach is usually:
Prepare
Model (for serialization, very little logic),
View Model (with property change bindings for view) and
View (thin layer, binds almost directly to View Model)
Write the majority of the application logic in the View Model.
Easier to have logic in here, so view bindings can work
This is the stage where the View Model layer bloats up
When the application is finally working, begin refactoring
For rich-client applications, I find my Model classes to be almost purely data
The View Model will most likely be refactored into 2 layers: MVM (Model-View-Model) and VVM (View-View Model)
MVM: This is where common, business-related logic/objects sit
MVM Objects contain truly common properties that any view can bind to
VVM: This is almost a 1-to-1 replication of a WPF view
These objects are typically never shared outside its own view
The separation into MVM and VVM helps prevent a single view model class from catering to ever views' needs (ie. whole bunch of Is(Selected|Checked|etc) and *Command, that may be only used exclusively by one view).
(For some people, VVM logic could probably be part of the View. But for me, I often find myself eventually wishing I had separated them in the first place, for testing. So now I do.)
As the application evolves, properties/methods can be either pushed from the MVM into the VVM, or vice versa.
The application's hierarchy is almost never truly static.
Even when you build the best version of the application possible, the client will simply want more.
Having the know-how to refactor an existing architecture to accommodate new requirements > Designing an architecture that is flexible enough for any future requirements
having said all that, for many applications that aren't too complex, a slightly-bulgy View Model is usually good enough.
I've been using MVVM for a while now with WPF. And i've learnt a lot over the course of development (going from never using it, to having a couple of applications developed in it)
However, recently I had some comments directed at the code which made me wonder if i'm doing things the right way. My current setup works (roughly) like this:
Model - Responsible for storing the data, data validation using
IDataErrorInfo and dirty tracking
ViewModel - Responsible for getting the data (from a repository like
pattern) and formatting it for a view's consumption (things like
filtering, ordering) also responsible for command handling from the
view (save, load, filter changes etc)
View - The usual UI stuff
Now it was mentioned to me that i should NEVER have business logic inside the model, and that the model should be as thin as possible, the viewmodel should be responsible for handling things such as data validation and dirty tracking.
I've seen comments and criticism on both sides of this, with people against and for putting logic in the model, What i have yet to see is any actual reasons for these sweeping statements. So id love to know if there is an actual reason i should be refactoring my setup.
Also, given that i do move the logic to the viewmodel, I can see the need for having multiple viewmodels where i currently have a single, for example:
Person - Model
PersonViewModel - Handles the dirty tracking, data validation etc
PersonsViewModel - Handles getting a collection of PersonViewModels,
filtering etc
PersonsView - The UI
This seems a little redundant, but perhaps i'm misunderstanding something. What I'm really looking for is some actual reasons for doing this one way or another, or if this is another argument like the use of code-behind in MVVM (pure opinion with little reasons etc)
High level description of MVVM:
View: User Interface
Model: Business logic and data (e.g Domain Model+Repositories, or Transaction Script+POCO entities, etc)
ViewModel: Data exposted to view in such form, that is easily consumable from view. Wikipedia's definition says: The view model is an abstraction of the view that exposes public properties and commands.
I like the Practical MVVM Manifesto (archived version) principes: Simplicity, Blendability, Designability, Testability.
This is very high level and abstract description and that's why you may find a lot of variations of MVVM. Whatever mvvm style you choose, keep in mind the responsibilities and principles and you should be ok. Try to avoid complexity. MVVM is not a silverbullet and you cannot cover all scenarios with single design pattern. One mvvm implementation may be suitable for one application but not for another. I, for example, build my mvvm architecture from scratch for each new project to ensure the best fit
When is comes to responsibilities:
Take validation as an example:
validation logic that password and repeat password inputs should be equal is clearly presentation logic and should be present in viewmodel. On the other side, there may be business rule, that password must contain at least one special character. This logic should reside in Model, however you may expose it in viewmodel to be easily consumable from view. It's a business logic, but you may need to present it somehow.
if you have application that only uses webservice to retrieve and store then your model will be probably just the data access components.
Here is couple of resources:
Wikipedia: https://en.wikipedia.org/wiki/Model_View_ViewModel.
MVVM is variation of Martin Fowler's MVP pattern, you may find it useful as well: http://martinfowler.com/eaaDev/PresentationModel.html
MSDN (Pattern and practices): https://msdn.microsoft.com/en-us/library/hh848246.aspx
I like to think of the Model layer as anything that has nothing to do with how the app is hosted (i.e. independent of WPF). It is one or more dlls that represent the business domain and the operations that need to be performed in it. If it would make sense to take theses same dlls and use them in a web application, windows service e.t.c then it is usually a sign that the split between Model and ViewModel is appropriate.
There's no simple answer to your question. The simplest answer is that the model and view model should contain the code that you should unit test. The separation between model and view model is a little less distinct. I like to keep the model as simple as possible and limit it to whatever is exchanged with the server tier. The view model should encapsulate the model, and provide any addition functionality (both business logic and abstract presentation logic) so that you can keep the presentation layer as simple as possible (declarative, in the case of WPF XAML).
I see it this way:
Model - Object that can be passed around. A Common type between different layers for communication.
ViewModel - Specifically created for Views. This should contain UI logic, for example, Data Annotations etc will go here. You might also call your web service methods here (assuming your actual business logic sits in a facade layer, or your database logic sits in a different layer/project) to populate the Views, dropdowns etc. You might end up with multiples of these per view, depending on your design.
View - UI Only.
I am not afraid to put external calls in the ViewModel
I understand the general reason why the Model-View-Presenter pattern is a good pattern. It separates the concern so that the same parts of code that deal with presenting information to the user do not worry about calculations, etc. My quesion is why do we need a view that essentially does nothing? All the view does is tell the presenter to do work and get the result back from the presenter. For example, in my C# views, I often just have a bunch of event handlers that call delegates that are implemented in the presenter. Why not just combine the view and the presenter? No concern is really separated because the view does not have any concern.
Two important advantages
We can write multiple views or replace views easily (for example WinForms => WPF implementation)
We increase the testability by creating test views for unit tests
Your View should simply be a way to get data to and from the user. Anything else that is not specifically related to that functionality should be pushed down into the Presenter (or model if it needs be). The presenter handles what the view gets but it should never be concerned with what view does once it gets it.
The presenter is an attempt to look at your "UI" in a more semantic manner. You may have 2 textboxes on your View but your Presenter sees Name and Surname. The idea should be that with the minimal amount of fuse you could lift the View off an pop another one on.
I don't know how much I agree with that and tend to prefer MVVM where you don't have Presenters, instead you have ViewModels which I feel are a better way to define the above abstraction.
I'm trying to create an silverlight application using the MVVM design pattern. It's a kind of bank application.
I've watched a lot of tutorials on MVVM but something makes me real confused.
I have about fiwe usercontrols representing my views "TransactionsView", "AccountView" etc and a bunch of models "UserProfile" - containing user password, username and a list of UserAccounts, "UserAccounts" - containing name, balance and a list of AccountTransactions, "AccountTransactions" - containing a name, and ammount.
Should i create one modelview which contains my userprofile or should i create a viewmodel for every view i have? I'm a doing right so far? Or have i got it completley wrong?
Thanks
In MVVM, ViewModels are usually 1-to-1 with Views. There isn't a parity between number of ViewModel and Models, though.
View: UI
ViewModel: Handles changes to view state, forwarding them to the model if/when appropriate. Sends notifications from the underlying program back to the user. It may also do initial UI validation.
Model: Actual "guts" of the application. Algorithms, data storage, system calls etc go here. I put program flow here. I've seen other people put it in the ViewModel. That part is up to you to figure out.
A View always needs a ViewModel, hence 1-to-1 (it could have sub-models, but I'll leave that up to you to decide on/deal with. I'd start off with 1-to-1).
A ViewModel usually needs Models to actually "do work", but how many classes/instances is up to each app/problem you're trying to solve.
From what you explain you are going in the right direction. What viewmodel you create is a bit up to you, MVVM is not set in stone - its just a method. What I found through trial and ERROR was that it was smart to understand it well before digging myself in too deep.
I read many articles that didn't explain MVVM in a way I could understand. Finally I found a couple of articles by Jeremiah Morrill that were straight to the point and easy to understand: Article 1 and article 2.
One ViewModel per view is recommended for MVVM.
There's no real hard and fast rules but essentially there's normally one ViewModel per View. You can get into a situation where you want to share a view model across multiple views but it's rare.
Imagine what you want to see on the screen and each state the screen / controls on the screen might be in, everything that is needed on that particular screen (view) should have a corresponding property in your ViewModel that you can bind the View to. So, this translate to a single ViewModel for a particular View. The ViewModel itself can be tied into one or more model(s) in the back. At least that's how I understand it.